Skip to content

Open-source Xbox-inspired desktop launcher for Xodus on Linux

TypeScript

fix(accounts): preserve independent player sessions across Store changes

domsvobodadfa6396b0d1e
diff --git a/scripts/ui/accounts-smoke.cjs b/scripts/ui/accounts-smoke.cjs
new file mode 100644
index 0000000..2187bc7
--- /dev/null
+++ b/scripts/ui/accounts-smoke.cjs
@@ -0,0 +1,80 @@
+// Run with Electron. Exercises only session-only demo account UI using synthetic identities.
+// XODUS_UI_SMOKE_OUTPUT must be a new private directory. Optional
+// XODUS_UI_SMOKE_SOURCE selects a built checkout (defaults to this checkout).
+// English-only synthetic account screenshots.
+const {app,session,ipcMain} = require('electron');
+const fs = require('node:fs/promises');
+const path = require('node:path');
+const {pathToFileURL} = require('node:url');
+const source = path.resolve(process.env.XODUS_UI_SMOKE_SOURCE || path.join(__dirname,'../..'));
+const output = process.env.XODUS_UI_SMOKE_OUTPUT;
+if (!output || !path.isAbsolute(output)) throw Error('Set XODUS_UI_SMOKE_OUTPUT to a new absolute private directory');
+if (process.argv.some(value=>value==='--launch-game'||value==='--nexus-profile')) throw Error('Demo fixture does not accept game or profile arguments');
+process.env.XODUS_DEMO = '1';
+app.disableHardwareAcceleration();
+const language='en-US';
+app.commandLine.appendSwitch('lang',language);
+// Never inherit another capture action or a developer server from the caller.
+for (const name of ['VITE_DEV_SERVER_URL','XODUS_DEMO_CAPTURE_DIR','XODUS_DEMO_TOUR','XODUS_NEXUS_SMOKE_SCREENSHOT','XODUS_NEXUS_SMOKE_STORE','XODUS_NEXUS_SMOKE_STORE_QUERY','XODUS_NEXUS_FONTCONFIG','XODUS_NEXUS_FONTCONFIG_ORIGINAL','XODUS_NEXUS_FONTCONFIG_ORIGINAL_SET']) delete process.env[name];
+// Block both main-process Store requests and renderer artwork. This fixture
+// needs no network and cannot accidentally fall through to live account APIs.
+globalThis.fetch = async () => { throw Error('Network disabled by demo UI fixture'); };
+let completed = false;
+const timer = setTimeout(()=>{console.error('Demo runtime-settings smoke timed out');app.exit(1);},30000);
+const evaluate = (window, fn, ...args) => window.webContents.executeJavaScript(`(${fn.toString()})(...${JSON.stringify(args)})`);
+const ready = async (window, selector) => evaluate(window, async selector => {
+ const deadline=Date.now()+6000;
+ while(!document.querySelector(selector)) {
+ if(Date.now()>deadline)throw Error('Missing demo element: '+selector);
+ await new Promise(resolve=>setTimeout(resolve,30));
+ }
+},selector);
+const settle = window => evaluate(window,async()=>{
+ await new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(resolve)));
+ await Promise.race([Promise.all(document.getAnimations().filter(animation=>Number.isFinite(animation.effect?.getTiming().iterations)).map(animation=>animation.finished.catch(()=>{}))),new Promise(resolve=>setTimeout(resolve,500))]);
+});
+async function capture(window) {
+ const results=[];
+ const snapshot=await evaluate(window,()=>window.launcher.getSnapshot());
+ if(snapshot.auth.username!=='[email protected]')throw Error('Expected isolated sample account');
+ await ready(window,'.sidebar nav button');
+ await evaluate(window,()=>[...document.querySelectorAll('.sidebar-bottom button')].find(button=>button.textContent.trim()==='Settings').click());
+ await ready(window,'.account-card');
+ for(const [width,height] of [[1280,800],[800,600]])for(const playerOnly of [false,true]) {
+ window.setContentSize(width,height);
+ const fixture=structuredClone(snapshot);
+ Object.assign(fixture.backend.capabilities,{playerAccount:true,savedAccounts:true,licenseProfile:true});
+ fixture.auth={running:false,stored:!playerOnly,username:playerOnly?undefined:'[email protected]',player:'[email protected]',gamertag:'PersonalPlayer',saved:['[email protected]','[email protected]'],note:playerOnly?'No Microsoft Store account is signed in.':'Synthetic Store licensing account with a separate Xbox player.'};
+ window.webContents.send('snapshot',fixture);await settle(window);
+ await evaluate(window,()=>document.querySelector('.account-card').scrollIntoView({block:'start'}));await settle(window);
+ const bounds=await evaluate(window,()=>({viewport:[innerWidth,innerHeight],documentWidth:document.documentElement.scrollWidth,language:document.documentElement.lang,cards:[...document.querySelectorAll('.account-card')].map(card=>({text:card.textContent,box:(()=>{const r=card.getBoundingClientRect();return {left:r.left,right:r.right,top:r.top,bottom:r.bottom};})()}))}));
+ if(bounds.documentWidth>width||bounds.language!=='en'||bounds.cards.length!==2||bounds.cards.some(card=>card.box.left<0||card.box.right>width))throw Error('Account UI bounds/language failed: '+JSON.stringify(bounds));
+ if(!bounds.cards[1].text.includes('[email protected]')||!bounds.cards[0].text.includes('[email protected]'))throw Error('Independent synthetic identities missing');
+ const state=playerOnly?'player-only':'dual';
+ await fs.writeFile(path.join(output,`accounts-${state}-${width}x${height}.png`),(await window.webContents.capturePage()).toPNG());
+ if(bounds.cards[1].box.bottom>height) {
+ await evaluate(window,()=>document.querySelectorAll('.account-card')[1].scrollIntoView({block:'center'}));await settle(window);
+ await fs.writeFile(path.join(output,`accounts-${state}-player-${width}x${height}.png`),(await window.webContents.capturePage()).toPNG());
+ }
+ results.push({state,width,height,...bounds});
+ }
+ await fs.writeFile(path.join(output,'account-results.json'),JSON.stringify({source,scope:'Compiled English session-only demo with distinct synthetic Store/player identities. Main fetch and renderer network disabled. No real credentials, backend, games or saves.',results},null,2)+'\n');
+ completed=true;clearTimeout(timer);app.exit(0);
+}
+(async()=>{
+ // Refuse an existing directory, so no saved profile or prior result is reused.
+ await fs.mkdir(output,{mode:0o700});
+ const profile=path.join(output,'profile');await fs.mkdir(profile,{mode:0o700});
+ app.setPath('userData',profile);
+ app.on('browser-window-created',(_event,window)=>{
+ window.show=()=>{};window.hide();window.webContents.setBackgroundThrottling(false);
+ window.webContents.once('did-finish-load',()=>void capture(window).catch(error=>{console.error(error);app.exit(1);}));
+ });
+ await app.whenReady();
+ session.defaultSession.webRequest.onBeforeRequest({urls:['http://*/*','https://*/*','ws://*/*','wss://*/*']},(_details,callback)=>callback({cancel:true}));
+ // Use the built-in offscreen smoke surface, while this fixture owns exit.
+ process.env.XODUS_NEXUS_SMOKE_SCREENSHOT=path.join(output,'built-in-smoke.png');
+ app.quit=()=>{};
+ await import(pathToFileURL(path.join(source,'dist-electron/main/index.js')).href);
+})().catch(error=>{console.error(error);clearTimeout(timer);app.exit(1);});
+app.on('will-quit',()=>{if(!completed)clearTimeout(timer);});
diff --git a/src/main/game-catalog-detail-ipc.test.ts b/src/main/game-catalog-detail-ipc.test.ts
index 88d55d0..f2f9811 100644
--- a/src/main/game-catalog-detail-ipc.test.ts
+++ b/src/main/game-catalog-detail-ipc.test.ts
@@ -61,3 +61,10 @@ it.each(['game-activity','game-achievements'])('%s uses the player identity and
f.authState.player='other-player';resolve({productId:'9AAAAAAAAAAA',xboxTitleId:'123'});
expect(await pending).toEqual({status:'error'});
});
+
+it.each(['game-activity','game-achievements'])('%s supports an independent player after Store sign-out',async route=>{
+ const f=fixture();f.authState.stored=false;f.authState.username='';f.authState.player='personal-player';
+ expect(await f.call(route,{productId:'9AAAAAAAAAAA'})).toMatchObject({status:'available'});
+ const selected=route==='game-activity'?f.gameActivities:f.gameAchievements;
+ expect(selected.select).toHaveBeenCalledWith('personal-player','/fixture/cli');
+});
diff --git a/src/main/index.ts b/src/main/index.ts
index 2baff76..69016a7 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -150,9 +150,8 @@ let gameGuide:XboxGameGuide;
let overlayShortcut:XboxOverlayShortcut|undefined;
const nativeSocialSnapshots:(()=>void)[]=[];
function nativeSocialConnection(){
- const status=backend?.current;
- // Xbox Live sees the player account when one is stored, otherwise the license account.
- return !demoMode&&!authState.running&&authState.stored===true&&authState.username&&status?.available&&status.binaryPath&&status.capabilities.nativeSocial?{account:authState.player??authState.username,binary:status.binaryPath}:undefined;
+ const status=backend?.current,account=authState.player??(authState.stored===true?authState.username:undefined);
+ return !demoMode&&!authState.running&&account&&status?.available&&status.binaryPath&&status.capabilities.nativeSocial?{account,binary:status.binaryPath}:undefined;
}
function resetNativeSocial(){for(const reset of nativeSocialResets)reset();xboxNativeSocial?.clear();resetSocialTransport();}
let nativeSocialBackend:string|undefined;
@@ -228,9 +227,10 @@ const launcherTray=new LauncherTray(()=>{
const walletUnlocker = new WalletUnlocker();
const xboxSocial = new XboxSocialSessions(() => {
const status = backend?.current;
- return !shutdownStarted && !authState.running && authState.stored === true && authState.username
+ const account = authState.player ?? (authState.stored === true ? authState.username : undefined);
+ return !shutdownStarted && !authState.running && account
&& status?.available && status.binaryPath && status.capabilities.commands.includes('social')
- ? { account: authState.player ?? authState.username, binary: status.binaryPath } : undefined;
+ ? { account, binary: status.binaryPath } : undefined;
});
const keyringSupport = new KeyringSupport(process.env, undefined, process.platform, undefined, {
diagnostic: value => backendDiagnostic({ operation: 'keyring', event: 'diagnostic', keyring: value, elapsedMs: value.elapsedMs }),
@@ -557,9 +557,9 @@ async function refreshAccount(emit = true, afterAuth = false): Promise<AuthStatu
const selectedAuth = authState;
accountLibrary.select(authState.stored === true ? authState.username : undefined,
status.capabilities.library ? status.binaryPath : undefined, currentMarket());
- gameActivities.select(authState.stored === true ? authState.player ?? authState.username : undefined,
+ gameActivities.select(authState.player ?? (authState.stored === true ? authState.username : undefined),
status.capabilities.gameActivity ? status.binaryPath : undefined);
- gameAchievements.select(authState.stored === true ? authState.player ?? authState.username : undefined,
+ gameAchievements.select(authState.player ?? (authState.stored === true ? authState.username : undefined),
status.capabilities.achievements ? status.binaryPath : undefined);
await accountProfile?.select(authState.player ?? (authState.stored === true ? authState.username : undefined),
status.capabilities.profile ? status.binaryPath : undefined, emit);
@@ -726,6 +726,8 @@ function requestSavedAccount(action: 'use' | 'forget', name: unknown): Promise<v
ensureIdle();
const binary = backend.current.binaryPath;
if (typeof name !== 'string' || !binary || !backend.current.capabilities.savedAccounts) return Promise.reject(Error('Saved accounts are not available.'));
+ if (action === 'forget' && authState.stored === null) return Promise.reject(Error('Refresh account status before forgetting a saved Store account.'));
+ const forgetActiveStore = action === 'forget' && name === authState.username;
const job = Promise.resolve().then(async () => {
authState = { ...authState, running: true };
accountRefresh.invalidate();
@@ -742,7 +744,10 @@ function requestSavedAccount(action: 'use' | 'forget', name: unknown): Promise<v
else await forgetSavedAccount(binary, name);
} finally {
accountRefresh.invalidate();
- try { if (!shutdownStarted) await refreshAccount(false, true); }
+ try {
+ try { if (forgetActiveStore) await revokeOffline('sign-out'); }
+ finally { if (!shutdownStarted) await refreshAccount(false, true); }
+ }
finally { authState.running = false; emitSnapshot(); }
}
});
@@ -890,6 +895,7 @@ async function prepareInstall(request: InstallRequest, updateGame?: Game, conten
}
async function runDownload(task: DownloadTask, binary: string, market: string, updateGame?: Game, content?: { game: Game; pkg: ContentPackage; manager: GameContent }): Promise<void> {
+ const installAccount = authState.stored === true ? authState.username : undefined;
const { id, productId, destination, selectedContentId } = task;
const structured = Boolean(backend.current.capabilities.streamingProgressJson);
const controllable = structured && Boolean(backend.current.capabilities.streamingControls);
@@ -986,7 +992,7 @@ async function runDownload(task: DownloadTask, binary: string, market: string, u
delete gameUpdates[updateGame.id];
}
}
- else await store.upsertGame({ ...inspected, licenseAccount: authState.username, offerProductId: /^[A-Z0-9]{12}$/.test(task.productId) ? task.productId : undefined });
+ else await store.upsertGame({ ...inspected, licenseAccount: installAccount, offerProductId: /^[A-Z0-9]{12}$/.test(task.productId) ? task.productId : undefined });
} catch (error) {
if (updateGame) await refreshIncompleteUpdate(updateGame).catch(() => {});
if (updateGame && task.status === 'complete') {
@@ -1150,11 +1156,20 @@ async function prepareGameLaunch(id: string, steam?: SteamGameContext): Promise<
// Changing Store credentials must not race a download using another account.
assertActivityCompatible(operations.keys(), store.downloads, gameOperation, installQueue.size);
// The game was installed with another saved Store account: use that one, no sign-in needed.
- for (const prepare of nativeSocialBeforeAuth) await prepare();
- resetNativeSocial(); xboxSocial.close();
- await useSavedAccount(backend.current.binaryPath, game.licenseAccount);
+ authState = { ...authState, running: true };
accountRefresh.invalidate();
- await refreshAccount(false, true);
+ emitSnapshot();
+ try {
+ for (const prepare of nativeSocialBeforeAuth) await prepare();
+ resetNativeSocial(); xboxSocial.close();
+ await accountProfile.select(undefined);
+ await licenseProfile?.select(undefined);
+ await useSavedAccount(backend.current.binaryPath, game.licenseAccount);
+ } finally {
+ accountRefresh.invalidate();
+ try { await refreshAccount(false, true); }
+ finally { authState.running = false; emitSnapshot(); }
+ }
if (authState.stored !== true || authState.username !== game.licenseAccount) throw Error('The saved Store account could not be activated. Sign in to it again.');
}
const inspected = await inspectGameDirectory(game.path);
@@ -2046,7 +2061,7 @@ function registerIpc(): void {
ipcMain.handle('game-activity', async (_event, id: unknown, refresh = false) => {
if (typeof refresh !== 'boolean') throw Error('Invalid activity request.');
const target=gameDetailsTarget(id,store.games),market=currentMarket();
- if (authState.running || authState.stored !== true || !authState.username) return { status: 'signed-out' };
+ if (authState.running || !(authState.player ?? (authState.stored === true ? authState.username : undefined))) return { status: 'signed-out' };
if (!backend.current.capabilities.gameActivity || !backend.current.binaryPath) return { status: 'unsupported' };
const account = authState.player ?? authState.username, binary = backend.current.binaryPath;
gameActivities.select(account, binary);
@@ -2054,15 +2069,15 @@ function registerIpc(): void {
try{title=target.game?await installedTitleId(target.game.path):await catalog.gameDetails(target.productId!,market).then(details=>details?.xboxTitleId);}
catch{return {status:'error'};}
if (!title) return { status: 'unavailable' };
- if (authState.running || authState.stored !== true || account !== (authState.player ?? authState.username) || binary !== backend.current.binaryPath || !target.game&&market!==currentMarket()) return { status: 'error' };
+ if (authState.running || (!authState.player && authState.stored !== true) || account !== (authState.player ?? authState.username) || binary !== backend.current.binaryPath || !target.game&&market!==currentMarket()) return { status: 'error' };
const activity = await gameActivities.get(title, refresh);
- if (authState.running || authState.stored !== true || account !== (authState.player ?? authState.username) || binary !== backend.current.binaryPath || !target.game&&market!==currentMarket()) return { status: 'error' };
+ if (authState.running || (!authState.player && authState.stored !== true) || account !== (authState.player ?? authState.username) || binary !== backend.current.binaryPath || !target.game&&market!==currentMarket()) return { status: 'error' };
return activity;
});
ipcMain.handle('game-achievements', async (_event, id: unknown, refresh = false) => {
if (typeof refresh !== 'boolean') throw Error('Invalid achievements request.');
const target=gameDetailsTarget(id,store.games),market=currentMarket();
- if (authState.running || authState.stored !== true || !authState.username) return { status: 'signed-out' };
+ if (authState.running || !(authState.player ?? (authState.stored === true ? authState.username : undefined))) return { status: 'signed-out' };
if (!backend.current.capabilities.achievements || !backend.current.binaryPath) return { status: 'unsupported' };
const account = authState.player ?? authState.username, binary = backend.current.binaryPath;
gameAchievements.select(account, binary);
@@ -2070,9 +2085,9 @@ function registerIpc(): void {
try{title=target.game?await installedTitleId(target.game.path):await catalog.gameDetails(target.productId!,market).then(details=>details?.xboxTitleId);}
catch{return {status:'error'};}
if (!title) return { status: 'unavailable' };
- if (authState.running || authState.stored !== true || account !== (authState.player ?? authState.username) || binary !== backend.current.binaryPath || !target.game&&market!==currentMarket()) return { status: 'error' };
+ if (authState.running || (!authState.player && authState.stored !== true) || account !== (authState.player ?? authState.username) || binary !== backend.current.binaryPath || !target.game&&market!==currentMarket()) return { status: 'error' };
const value = await gameAchievements.get(title, refresh);
- if (authState.running || authState.stored !== true || account !== (authState.player ?? authState.username) || binary !== backend.current.binaryPath || !target.game&&market!==currentMarket()) return { status: 'error' };
+ if (authState.running || (!authState.player && authState.stored !== true) || account !== (authState.player ?? authState.username) || binary !== backend.current.binaryPath || !target.game&&market!==currentMarket()) return { status: 'error' };
return value;
});
ipcMain.handle('launch-game', (_event, id: string) => launchGame(id));
diff --git a/src/main/multi-account.test.ts b/src/main/multi-account.test.ts
index e9afc97..b799831 100644
--- a/src/main/multi-account.test.ts
+++ b/src/main/multi-account.test.ts
@@ -13,7 +13,7 @@ function savedFixture() {
const context: Record<string, any> = {
authState: { stored: true, username: 'store-one', player: 'personal-player', running: false },
backend: { current: { binaryPath: '/synthetic/cli', capabilities: { savedAccounts: true } } },
- authJob: undefined, shutdownStarted: false,
+ authJob: undefined, shutdownStarted: false, revokeOffline: vi.fn(async () => {}),
accountRefresh: { invalidate: () => calls.push('invalidate') },
accountLibrary: { reset: () => calls.push('library-reset') },
gameActivities: { select: vi.fn() }, gameAchievements: { select: vi.fn() },
@@ -31,7 +31,7 @@ function savedFixture() {
const start = source.indexOf('function requestSavedAccount(');
const code = ts.transpileModule(source.slice(start, source.indexOf('async function startInstall(', start)), { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText;
runInNewContext(code, context);
- return { context, calls, finish, request: (action: string) => context.requestSavedAccount(action, 'store-two') as Promise<void> };
+ return { context, calls, finish, request: (action: string, name = 'store-two') => context.requestSavedAccount(action, name) as Promise<void> };
}
it.each(['use', 'forget'])('serializes %s before its first await and reconciles identity before unlocking', async action => {
@@ -67,19 +67,41 @@ it('parses only bounded valid saved identities and rejects malformed envelopes',
await expect(forgetSavedAccount('/never-executed', '')).rejects.toThrow('Invalid account');
});
-it.each([false,true])('automatically selects the install Store account without changing player identity (download busy: %s)', async busy => {
- const use=vi.fn(async()=>{}),authState={stored:true,username:'other-store',player:'personal-player'};
+it.each(['success','busy','timeout'])('automatically selects the install Store account without changing player identity (%s)', async mode => {
+ const busy=mode==='busy';let release!:()=>void;const gate=new Promise<void>(resolve=>release=resolve);
+ const use=vi.fn(async()=>{await gate;if(mode==='timeout')throw Error('timeout after commit');}),authState={stored:true,username:'other-store',player:'personal-player'};
const context:any={game:{licenseAccount:'install-store'},authState,savedAccounts:['install-store'],
backend:{current:{binaryPath:'/synthetic/cli',capabilities:{savedAccounts:true}}},
operations:new Map(),store:{downloads:[]},gameOperation:undefined,installQueue:{size:busy?1:0},
assertActivityCompatible,nativeSocialBeforeAuth:[],resetNativeSocial:vi.fn(),xboxSocial:{close:vi.fn()},
- useSavedAccount:use,accountRefresh:{invalidate:vi.fn()},
- refreshAccount:async()=>{authState.username='install-store';}};
+ useSavedAccount:use,accountRefresh:{invalidate:vi.fn()},emitSnapshot:vi.fn(),accountProfile:{select:vi.fn(async()=>{})},licenseProfile:undefined,
+ refreshAccount:async()=>{context.authState.username='install-store';}};
const start=source.indexOf(' if (game.licenseAccount &&',source.indexOf('async function prepareGameLaunch('));
const block=source.slice(start,source.indexOf(' const inspected',start));
const code=ts.transpileModule('async function selectInstallAccount(){'+block+'}',{compilerOptions:{target:ts.ScriptTarget.ES2022}}).outputText;
runInNewContext(code,context);
if(busy){await expect(context.selectInstallAccount()).rejects.toThrow('Another Xodus operation');expect(use).not.toHaveBeenCalled();}
- else {await context.selectInstallAccount();expect(use).toHaveBeenCalledWith('/synthetic/cli','install-store');expect(authState.username).toBe('install-store');}
+ else {const job=context.selectInstallAccount();await vi.waitFor(()=>expect(use).toHaveBeenCalled());expect(context.authState.running).toBe(true);release();if(mode==='timeout')await expect(job).rejects.toThrow('timeout after commit');else await job;expect(context.authState.running).toBe(false);expect(use).toHaveBeenCalledWith('/synthetic/cli','install-store');expect(context.authState.username).toBe('install-store');}
expect(authState.player).toBe('personal-player');
});
+
+it('revokes offline licenses when forgetting the active Store, leaving other saved accounts alone', async () => {
+ for(const name of ['store-one','store-two']) {
+ const f=savedFixture(),job=f.request('forget',name);f.finish();await job;
+ expect(f.context.revokeOffline).toHaveBeenCalledTimes(name==='store-one'?1:0);
+ }
+});
+
+it('reconciles active Forget despite offline cleanup failure and releases the reservation', async () => {
+ const f=savedFixture();f.context.revokeOffline.mockRejectedValueOnce(Error('cleanup blocked'));
+ const job=f.request('forget','store-one');f.finish();
+ await expect(job).rejects.toThrow('cleanup blocked');
+ expect(f.context.refreshAccount).toHaveBeenCalledWith(false,true);
+ expect(f.context.authState.running).toBe(false);expect(f.context.authJob).toBeUndefined();
+});
+
+it('requires readable active Store status before Forget can mutate credentials', async () => {
+ const f=savedFixture();f.context.authState.stored=null;
+ await expect(f.request('forget')).rejects.toThrow('Refresh account status');
+ expect(f.context.forgetSavedAccount).not.toHaveBeenCalled();expect(f.context.authJob).toBeUndefined();
+});
diff --git a/src/renderer/App.tsx b/src/renderer/App.tsx
index de6f039..8afa3a3 100644
--- a/src/renderer/App.tsx
+++ b/src/renderer/App.tsx
@@ -1040,7 +1040,7 @@ export function SettingsPage({ data, toast }: { data: AppSnapshot; toast: (value
<strong>{name}</strong>
{name === data.auth.username ? <span className="status-label ready">{ui("ui.account_in_use_5b09d3f")}</span>
: <button className="secondary" disabled={data.auth.running} onClick={() => invoke('use-account', () => window.launcher.useAccount(name), ui("ui.account_switched_6a2e91c"))}>{ui("ui.use_this_account_e71c0a8")}</button>}
- <button className="secondary" disabled={data.auth.running} onClick={() => invoke('forget-account', () => window.launcher.forgetAccount(name), ui("ui.account_forgotten_c05d7e3"))}>{ui("ui.forget_account_3d8f6b1")}</button>
+ <button className="secondary" disabled={data.auth.running || data.auth.stored === null} onClick={() => invoke('forget-account', () => window.launcher.forgetAccount(name), ui("ui.account_forgotten_c05d7e3"))}>{ui("ui.forget_account_3d8f6b1")}</button>
</div>)}
<small>{ui("ui.saved_store_accounts_help_94be2d0")}</small>
</div> : null}
@@ -1294,7 +1294,7 @@ export default function App() {
if (loading) return <div className="boot"><div className="brand-mark">X</div><LoaderCircle className="spin" /><span>{ui("ui.loading_xodus_nexus_2e92cfd")}</span></div>;
return <ConfirmationProvider><PackageInstallProvider><div className="app-shell">
{!data.settings.firstRunCompleted ? <FirstRunWizard data={data} toast={(value) => setToast(value)} /> : null}
- <Sidebar data={data} page={page} go={go} openGame={openLibraryGame} openProfile={() => data.auth.stored === true && data.backend.capabilities.nativeSocial ? action(() => window.launcher.nativeSocial.openXboxPlayerProfile('me')) : go('settings')} inert={socialOpen} notifications={<NotificationBell key={JSON.stringify([data.auth.player??data.auth.username,data.backend.binaryPath])} notices={notifications.notices} failed={notifications.failed} unsupported={notifications.unsupported} onSelect={notice=>{
+ <Sidebar data={data} page={page} go={go} openGame={openLibraryGame} openProfile={() => (data.auth.player || data.auth.stored === true) && data.backend.capabilities.nativeSocial ? action(() => window.launcher.nativeSocial.openXboxPlayerProfile('me')) : go('settings')} inert={socialOpen} notifications={<NotificationBell key={JSON.stringify([data.auth.player??data.auth.username,data.backend.binaryPath])} notices={notifications.notices} failed={notifications.failed} unsupported={notifications.unsupported} onSelect={notice=>{
notifications.acknowledge(notice);
if(notice.kind==='update')openLibraryGame(notice.target);
else{setSocialChat(previous=>({id:(previous?.id??0)+1,xuid:notice.target,identity:JSON.stringify([data.auth.player??data.auth.username,data.backend.binaryPath])}));setSocialMounted(true);setSocialOpen(true);}
diff --git a/src/renderer/Friends.tsx b/src/renderer/Friends.tsx
index cf693fe..143e950 100644
--- a/src/renderer/Friends.tsx
+++ b/src/renderer/Friends.tsx
@@ -9,7 +9,7 @@ import './friends.css';
// Warm only after pointer/keyboard intent, never on startup or while signing in.
export function preloadFriends(data:AppSnapshot,load:()=>Promise<unknown>=()=>window.launcher.getXboxFriends()):void {
- if(data.auth.stored!==true||data.auth.running||!data.backend.available||!data.backend.capabilities.commands.includes('social'))return;
+ if((data.auth.stored!==true&&!data.auth.player)||data.auth.running||!data.backend.available||!data.backend.capabilities.commands.includes('social'))return;
void load().catch(()=>{});
}
@@ -31,7 +31,7 @@ export function Friends({ data, close, docked=false }: { data: AppSnapshot; clos
const generation=useRef(0),pending=useRef(false),select=useRef('');
const currentFriend=useRef<XboxFriend>(),lastFriends=useRef(0);
const dialog=useRef<HTMLElement>(null),onClose=useRef(close);onClose.current=close;
- const available=data.auth.stored===true&&!data.auth.running&&data.backend.available&&data.backend.capabilities.commands.includes('social');
+ const available=(data.auth.stored===true||Boolean(data.auth.player))&&!data.auth.running&&data.backend.available&&data.backend.capabilities.commands.includes('social');
useEffect(()=>{
const origin=document.activeElement instanceof HTMLElement?document.activeElement:undefined;
dialog.current?.querySelector<HTMLElement>('[data-gamepad-initial]')?.focus({preventScroll:true});
@@ -134,7 +134,7 @@ export function Friends({ data, close, docked=false }: { data: AppSnapshot; clos
{incoming.map(invite=><article key={invite.id}><div><strong>{invite.game}</strong><small>{ui('friends.invitation_from', { name: invite.sender })}</small></div><button disabled={busy} onClick={()=>void invitationAction(()=>window.launcher.acceptGameInvite(invite.id))}>{ui("ui.accept_89713b9")}</button></article>)}
{outgoing.map(invite=><article key={invite.id}><div><strong>{invite.game}</strong><small>{invite.phase==='choosing'?ui("ui.choose_a_friend_below_then_send_an_invitation_27e80a3"):invite.phase==='sending'?ui("ui.waiting_for_the_game_to_send_the_invitation_c4d60eb"):invite.phase==='sent'?ui("ui.invitation_sent_b413595"):invite.phase==='failed'?ui("ui.the_game_could_not_confirm_invitation_delivery_d434e95"):ui("ui.invitation_cancelled_134517d")}</small></div>{invite.phase==='choosing'?<><button disabled={busy||!selected} onClick={()=>selected&&void invitationAction(()=>window.launcher.chooseGameInviteRecipient(invite.id,selected.xuid))}>{ui('friends.invite_friend', { name: selected?.gamertag ?? ui('friends.friend') })}</button><button disabled={busy} onClick={()=>void invitationAction(()=>window.launcher.cancelGameInvite(invite.id))}>{ui("ui.cancel_19766ed")}</button></>:null}</article>)}
</section>:null}
- {!available?<p role="status">{data.auth.stored!==true?ui("ui.sign_in_to_your_microsoft_account_in_settings_fi_187cd60"):ui("ui.this_backend_does_not_support_xbox_friends_and_c_6ed1034")}</p>:<>
+ {!available?<p role="status">{(data.auth.stored!==true&&!data.auth.player)?ui("ui.sign_in_to_your_microsoft_account_in_settings_fi_187cd60"):ui("ui.this_backend_does_not_support_xbox_friends_and_c_6ed1034")}</p>:<>
{error?<p className="friends-error" role="alert">{uiText(error)}</p>:null}
<div className="friends-columns">
<aside aria-label={ui("ui.friends_list_e79cc91")}>
diff --git a/src/renderer/Notifications.tsx b/src/renderer/Notifications.tsx
index 5417272..6974e44 100644
--- a/src/renderer/Notifications.tsx
+++ b/src/renderer/Notifications.tsx
@@ -7,9 +7,9 @@ import { ui } from './i18n';
import './notifications.css';
export function useNotifications(data:AppSnapshot) {
- const account=data.auth.player??data.auth.username;
- const identity=JSON.stringify([data.auth.stored===true?account:null,data.backend.binaryPath]);
- const storageKey=data.auth.stored===true&&account?'nexus.notifications.v1.'+encodeURIComponent(account):undefined;
+ const account=data.auth.player??(data.auth.stored===true?data.auth.username:undefined);
+ const identity=JSON.stringify([account??null,data.backend.binaryPath]);
+ const storageKey=account?'nexus.notifications.v1.'+encodeURIComponent(account):undefined;
const [reads,setReads]=useState<{identity:string;keys:string[]}>({identity:'',keys:[]});
const [inbox,setInbox]=useState<{identity:string;value:XboxConversation[]}>();
const [names,setNames]=useState<{identity:string;value:Map<string,string>}>();
@@ -17,7 +17,7 @@ export function useNotifications(data:AppSnapshot) {
const snapshot=useRef(data);snapshot.current=data;
const currentIdentity=useRef(identity);currentIdentity.current=identity;
const lastViewed=useRef<{identity:string;keys:string[]}>({identity,keys:[]});
- const supported=data.auth.stored===true&&!data.auth.running&&data.backend.available&&data.backend.capabilities.nativeSocial===true;
+ const supported=Boolean(account)&&!data.auth.running&&data.backend.available&&data.backend.capabilities.nativeSocial===true;
useEffect(()=>{
let keys:string[]=[];
try{if(storageKey)keys=parseNotificationReads(localStorage.getItem(storageKey));}catch{/* Read state is optional if storage is unavailable. */}
@@ -83,7 +83,7 @@ export function useNotifications(data:AppSnapshot) {
return()=>{active=false;clearInterval(timer);};
},[identity]);
const notices=notificationItems(data,supported&&inbox?.identity===identity?inbox.value:undefined,names?.identity===identity?names.value:new Map(),reads.identity===identity?reads.keys:[]);
- return {notices,readKeys:reads.identity===identity?reads.keys:[],failed:supported&&failed,unsupported:data.auth.stored===true&&!data.backend.capabilities.nativeSocial,
+ return {notices,readKeys:reads.identity===identity?reads.keys:[],failed:supported&&failed,unsupported:Boolean(account)&&!data.backend.capabilities.nativeSocial,
acknowledge:(notice:Notice)=>{if(notice.kind==='update')remember([notice.key]);},
viewed:(peer:string,ids:string[])=>{
const keys=ids.map(id=>messageNoticeKey(peer,id));
diff --git a/src/renderer/XboxChatDesktop.tsx b/src/renderer/XboxChatDesktop.tsx
index e3f292f..fd1720c 100644
--- a/src/renderer/XboxChatDesktop.tsx
+++ b/src/renderer/XboxChatDesktop.tsx
@@ -15,7 +15,7 @@ export function XboxChatDesktop({xuid}:{xuid:string}){
return()=>document.removeEventListener('visibilitychange',visible);
},[]);
const auth=snapshot?.auth;
- const account=auth?.stored===true&&!auth.running?(auth.player??auth.username):undefined;
+ const account=auth&&!auth.running?(auth.player??(auth.stored===true?auth.username:undefined)):undefined;
const binary=snapshot?.backend.binaryPath;
const supported=Boolean(snapshot?.backend.available&&snapshot.backend.capabilities.nativeSocial&&binary);
const problems={account:ui('social.desktop_account_failed'),close:ui('social.desktop_close_failed'),profile:ui('social.desktop_profile_failed')};
diff --git a/src/renderer/XboxSocial.tsx b/src/renderer/XboxSocial.tsx
index f20a6ec..862f77c 100644
--- a/src/renderer/XboxSocial.tsx
+++ b/src/renderer/XboxSocial.tsx
@@ -28,7 +28,7 @@ export function XboxSocial({auth,api,voice,overlay=false,shelf=false,close,openO
const [profiles,setProfiles]=useState<Record<string,XboxPlayerProfile>>({});
const [partyRecipient,setPartyRecipient]=useState<{xuid:string;gamertag:string}>();
const generation=useRef(0);
- const identity=auth.stored===true&&!auth.running?(auth.player??auth.username):undefined;
+ const identity=!auth.running?(auth.player??(auth.stored===true?auth.username:undefined)):undefined;
const selectedPerson=friends.find(person=>person.xuid===selected);
const selectedConversation=inbox.find(row=>row.participants.includes(selected??''));
const selectedName=selectedPerson?.gamertag??selectedConversation?.gamertag??'Xbox player';
diff --git a/src/renderer/guide-main.tsx b/src/renderer/guide-main.tsx
index 63bae86..b6f5acf 100644
--- a/src/renderer/guide-main.tsx
+++ b/src/renderer/guide-main.tsx
@@ -41,7 +41,7 @@ function XboxGameGuide(){
return()=>{unsubscribe();profiles();preferences();invitations();visibility();languages();disconnect();};
},[]);
useEffect(()=>{setChats([]);chatIds.current=[];setProfile(undefined);setExpanded(false);},[auth.username,auth.player]);
- const account=auth.stored===true&&!auth.running?(auth.player??auth.username):undefined;
+ const account=!auth.running?(auth.player??(auth.stored===true?auth.username:undefined)):undefined;
return <main className={'game-guide-shell'+(overlay.overlaySide==='right'?' is-right':'')} aria-label={ui("social.in_game_xbox_guide_b68219")}>
<div className={'game-guide-panel'+(expanded?' is-expanded':'')}>
{expanded?<div className="game-guide-full-toolbar"><button onClick={()=>setExpanded(false)}>{overlay.overlaySide==='right'?<PanelRightClose/>:<PanelLeftClose/>}{ui("social.return_to_shelf_4df4fc")}</button><span>{ui("social.xbox_social_9dd063")}</span></div>:null}
diff --git a/src/renderer/multi-account.test.tsx b/src/renderer/multi-account.test.tsx
index acd0959..6b42f38 100644
--- a/src/renderer/multi-account.test.tsx
+++ b/src/renderer/multi-account.test.tsx
@@ -39,7 +39,7 @@ it('keeps notification reads and broker acknowledgements scoped to the effective
expect(notices.readKeys).toEqual([key]);
await act(async () => notices.viewed('42', ['two']));
expect(window.launcher.viewedXboxChat).toHaveBeenLastCalledWith('player-one', '/synthetic/cli', '42', ['two']);
- data.auth = { ...data.auth, player: 'player-two' };
+ data.auth = { ...data.auth, stored: false, username: undefined, player: 'player-two' };
await act(async () => root.render(<Fixture />));
expect(notices.readKeys).toEqual([]);
await act(async () => notices.viewed('43', ['three']));