Open-source Xbox-inspired desktop launcher for Xodus on Linux
TypeScript
feat: coordinate frozen component update plans with owned admission
domsvobodaf2a6f565a8c3
diff --git a/src/main/backend-update-outcomes.test.ts b/src/main/backend-update-outcomes.test.tsindex 4f989bf..0395d85 100644--- a/src/main/backend-update-outcomes.test.ts+++ b/src/main/backend-update-outcomes.test.ts@@ -56,6 +56,22 @@ describe('backend mutation boundaries', () => {const oldRefresh = m.refresh(); await entered.promise; await m.update(() => {}); release.resolve(); await oldRefresh;expect(m.current.binaryPath).toBe(path.join(root, 'selected/xodus-cli')); expect(m.current.commit).toBe(backendLock.commit); expect(m.current.recipeSha256).toBe(backendRecipeSha256);});+ it('prepares no install for an absent, external or locally built backend', async () => {+ const m=manager(); for (const source of ['none','external','managed']) {+ Object.assign((m as unknown as {status:object}).status,{available:source!=='none',source});+ await fs.writeFile(path.join(root,'xodus-backends/current.json'),JSON.stringify({binaryPath:'/local',delivery:'local'}));+ expect((await m.prepareComponentUpdate(()=>{})).item.state).toBe('skipped');+ }+ expect(discoverBackend).not.toHaveBeenCalled(); expect(installBackend).not.toHaveBeenCalled();+ });+ it('applies only its prepared target and rejects a pointer changed after planning', async () => {+ const m=manager(),pointer=path.join(root,'xodus-backends/current.json');+ await fs.writeFile(pointer,JSON.stringify({binaryPath:'/old',delivery:'release',version:'1.0.0'}));+ Object.assign((m as unknown as {status:object}).status,{available:true,source:'managed',binaryPath:'/old'});+ const prepared=await m.prepareComponentUpdate(()=>{});expect(prepared.item.state).toBe('ready');+ await fs.writeFile(pointer,'changed');expect(await prepared.isCurrent()).toBe(false);+ await expect(prepared.apply({identity:Symbol()})).rejects.toMatchObject({committed:false});expect(installBackend).not.toHaveBeenCalled();+ });it('keeps operation target A while concurrent discovery records newer B', async () => {const m = manager(), entered = deferred<void>(), release = deferred<void>(); refreshSelected(m);vi.mocked(discoverBackend).mockResolvedValueOnce(artifact('99.0.0')).mockResolvedValueOnce(artifact('100.0.0'));diff --git a/src/main/backend.ts b/src/main/backend.tsindex b401bba..cc877ce 100644--- a/src/main/backend.ts+++ b/src/main/backend.ts@@ -6,6 +6,7 @@ import { parseBackendHelp } from '../shared/utils.js';import { run } from './process.js';import { backendLock, backendRecipeSha256, compareVersions } from './backend-package.js';import { discoverBackend, installBackend, type BackendArtifact } from './backend-releases.js';+import type { PreparedComponentUpdate } from './component-updates.js';import { BackendPrerequisiteError, backendPrerequisiteFailure } from './backend-prerequisites.js';const REPOSITORY = backendLock.repository;@@ -215,7 +216,40 @@ export class BackendManager {return this.current;}- async update(onStatus: () => void): Promise<void> {+ async prepareComponentUpdate(onStatus: () => void): Promise<PreparedComponentUpdate> {+ const before = await fs.readFile(this.pointerFile, 'utf8').catch(() => undefined);+ const externalRoot = this.status.externalRoot;+ let pointer: ManagedPointer | undefined;+ try { pointer = before === undefined ? undefined : JSON.parse(before) as ManagedPointer; } catch { /* Ineligible malformed pointer. */ }+ const eligible = this.status.available && this.status.source === 'managed' && pointer?.delivery === 'release' && pointer.binaryPath === this.status.binaryPath;+ const item = { id: 'backend', component: 'backend' as const, label: 'Backend', currentVersion: pointer?.version,+ state: 'skipped' as 'ready' | 'skipped' | 'unchanged', reason: 'Only an installed managed backend release is updated automatically.' };+ let target: BackendMutationTarget | undefined;+ const same = async () => before === await fs.readFile(this.pointerFile, 'utf8').catch(() => undefined) && externalRoot === this.status.externalRoot;+ if (!eligible || !pointer) return { item, isCurrent: same, apply: async () => { throw Error(item.reason); } };+ const artifact = await discoverBackend(this.fetcher);+ const newer = !pointer.version || compareVersions(pointer.version, artifact.manifest.version) < 0;+ return {+ item: { ...item, targetVersion: artifact.manifest.version, state: newer ? 'ready' : 'unchanged', reason: undefined },+ isCurrent: same,+ apply: async () => {+ try { await this.performUpdate(onStatus, artifact, same); target = { commit: this.status.commit!, binaryPath: this.status.binaryPath!, version: this.status.version, delivery: this.status.delivery }; }+ catch (error) { if (error instanceof BackendMutationError && error.committed) target = error.target; throw error; }+ return { committed: true };+ },+ reconcile: async () => {+ const pointer = await this.readPointer();+ if (!target || pointer?.binaryPath !== target.binaryPath || pointer.commit !== target.commit || pointer.version !== target.version) throw Error('The activated backend changed. Check again.');+ const refreshed = await this.refresh();+ if (!refreshed.available || refreshed.source !== 'managed' || refreshed.binaryPath !== target.binaryPath) throw Error('The activated backend is not available.');+ onStatus(); return {};+ },+ };+ }++ async update(onStatus: () => void): Promise<void> { return this.performUpdate(onStatus); }++ private async performUpdate(onStatus: () => void, selected?: BackendArtifact, expectedCurrent?: () => Promise<boolean>): Promise<void> {if (this.status.updating) throw new Error('A backend installation is already running.');// Reserve before the first awaited external activity check. Notification// failures must also release this reservation.@@ -231,7 +265,8 @@ export class BackendManager {await this.assertUpdateAllowed();// Keep this operation's verified target independent of later read-only// release checks, which may replace the manager's discovery cache.- const artifact = await discoverBackend(this.fetcher);+ if (expectedCurrent && !await expectedCurrent()) throw Error('The installed backend changed. Check again.');+ const artifact = selected ?? await discoverBackend(this.fetcher);this.artifact = artifact;const binaryPath = await installBackend(this.managedRoot, artifact, this.fetcher, async cli => {const caps = await this.validate(cli);@@ -244,6 +279,7 @@ export class BackendManager {this.status.phase = message; this.emitLog('backend', message); onStatus();});await this.assertUpdateAllowed();+ if (expectedCurrent && !await expectedCurrent()) throw Error('The installed backend changed before activation. Check again.');const manifest = artifact.manifest;const pointer: ManagedPointer = { commit: manifest.commit, binaryPath, builtAt: new Date().toISOString(),linuxRunPatch: manifest.compatibility, recipeSha256: manifest.recipeSha256, version: manifest.version, delivery: 'release' };diff --git a/src/main/component-update-admission.test.ts b/src/main/component-update-admission.test.tsnew file mode 100644index 0000000..ca3bd46--- /dev/null+++ b/src/main/component-update-admission.test.ts@@ -0,0 +1,19 @@+import { describe, expect, it, vi } from 'vitest';+import { ComponentUpdateAdmission } from './component-update-admission.js';+describe('component update admission', () => {+ it('reserves synchronously, rejects foreign owners, and expires released ownership', () => {+ const idle = vi.fn(), gate = new ComponentUpdateAdmission(idle), owner = gate.reserve();+ expect(gate.busy).toBe(true); expect(idle).toHaveBeenCalledOnce();+ expect(() => gate.reserve()).toThrow('progress'); expect(() => gate.assertAllowed()).toThrow('progress');+ expect(() => gate.assertAllowed({ identity: owner.identity })).toThrow('progress');+ expect(() => gate.assertAllowed(owner)).not.toThrow(); gate.release(owner);+ expect(gate.busy).toBe(false); expect(() => gate.assertAllowed(owner)).toThrow('expired');+ const next = gate.reserve(); expect(() => gate.release(owner)).toThrow(); gate.release(next);+ });+ it('never bypasses activity checks with the valid owner', () => {+ let active = false; const gate = new ComponentUpdateAdmission(() => { if (active) throw Error('active'); });+ active = true; expect(() => gate.reserve()).toThrow('active'); expect(gate.busy).toBe(false);+ active = false; const owner = gate.reserve(); active = true;+ expect(() => gate.assertActivity(owner)).toThrow('active'); gate.release(owner); expect(gate.busy).toBe(false);+ });+});diff --git a/src/main/component-update-admission.ts b/src/main/component-update-admission.tsnew file mode 100644index 0000000..e7e66d1--- /dev/null+++ b/src/main/component-update-admission.ts@@ -0,0 +1,26 @@+/** Process-local ownership only. No renderer-supplied value can acquire ownership. */+export interface ComponentUpdateOwner { readonly identity: symbol }+export class ComponentUpdateAdmission {+ private owner?: ComponentUpdateOwner;+ constructor(private readonly assertActivityIdle: () => void) {}+ get busy(): boolean { return this.owner !== undefined; }+ assertAllowed(owner?: ComponentUpdateOwner): void {+ if (this.owner && owner !== this.owner) throw Error('Component updates are in progress.');+ if (owner && owner !== this.owner) throw Error('The component update reservation has expired.');+ }+ reserve(): ComponentUpdateOwner {+ this.assertAllowed();+ this.assertActivityIdle();+ const owner = Object.freeze({ identity: Symbol('component-update') });+ this.owner = owner;+ return owner;+ }+ assertActivity(owner: ComponentUpdateOwner): void {+ this.assertAllowed(owner);+ this.assertActivityIdle();+ }+ release(owner: ComponentUpdateOwner): void {+ this.assertAllowed(owner);+ this.owner = undefined;+ }+}diff --git a/src/main/component-updates.test.ts b/src/main/component-updates.test.tsnew file mode 100644index 0000000..a9df4de--- /dev/null+++ b/src/main/component-updates.test.ts@@ -0,0 +1,43 @@+import { describe, expect, it, vi } from 'vitest';+import { ComponentUpdates, type PreparedComponentUpdate } from './component-updates.js';+import { ComponentUpdateAdmission } from './component-update-admission.js';+const deferred = () => { let resolve!: () => void; const promise = new Promise<void>(r => { resolve = r; }); return { promise, resolve }; };+function entry(id: string, component: 'backend' | 'runtime' | 'launcher' = 'runtime'): PreparedComponentUpdate { return { item: { id, component, label: id, state: 'ready' }, isCurrent: vi.fn(async () => true), apply: vi.fn(async () => ({ committed: true })) }; }+function fixture(entries: PreparedComponentUpdate[], changed = () => {}) { const idle = vi.fn(); const admission = new ComponentUpdateAdmission(idle); const updates = new ComponentUpdates(admission, async () => entries, changed, () => false); return { updates, admission, idle }; }+describe('component update coordinator', () => {+ it('orders backend, installed families then launcher and never overlaps child applies', async () => {+ const a = entry('backend', 'backend'), b = entry('standard'), c = entry('launcher', 'launcher'), order: string[] = []; let active = false;+ for (const e of [a,b,c]) e.apply = vi.fn(async owner => { expect(owner).toBeDefined(); expect(active).toBe(false); active = true; await Promise.resolve(); order.push(e.item.id); active = false; return { committed: true }; });+ const {updates} = fixture([c,b,a]); const plan = await updates.plan(); const result = await updates.apply(plan.id); expect(order).toEqual(['backend','standard','launcher']); expect(result.items.every(row => row.outcome === 'updated')).toBe(true);+ });+ it('blocks other mutations and concurrent batches throughout held child work, then releases', async () => {+ const e = entry('standard'), hold = deferred(); e.apply = vi.fn(async () => { await hold.promise; return { committed:true }; });+ const {updates,admission} = fixture([e]); const plan = await updates.plan(), pending = updates.apply(plan.id);+ expect(admission.busy).toBe(true); expect(() => admission.assertAllowed()).toThrow(); await expect(updates.apply(plan.id)).rejects.toThrow(); hold.resolve(); await pending; expect(admission.busy).toBe(false);+ });+ it('does not install missing, external or prerequisite-deferred items', async () => {+ const entries = ['skipped','unchanged','deferred'].map((state,i) => ({...entry(String(i)), item:{...entry(String(i)).item,state:state as 'skipped'|'unchanged'|'deferred',reason:'not eligible'}}));+ const {updates} = fixture(entries); const plan = await updates.plan(), result = await updates.apply(plan.id); expect(result.items.map(row => row.outcome)).toEqual(['skipped','unchanged','deferred']); for (const e of entries) expect(e.apply).not.toHaveBeenCalled();+ });+ it('rejects changed installed identity and stops before launcher', async () => {+ const a=entry('a'),b=entry('launcher','launcher'); a.isCurrent=vi.fn(async()=>false); const {updates}=fixture([a,b]);const plan=await updates.plan(),r=await updates.apply(plan.id); expect(r.items.map(row=>row.outcome)).toEqual(['stale','not-run']);expect(a.apply).not.toHaveBeenCalled();expect(b.apply).not.toHaveBeenCalled();+ });+ it('retries committed attention by reconciliation only, never reinstallation', async () => {+ const e=entry('a');e.apply=vi.fn(async()=>{throw Object.assign(Error('account refresh'),{committed:true});});e.reconcile=vi.fn(async()=>({})); const {updates}=fixture([e]);const plan=await updates.plan(),first=await updates.apply(plan.id);expect(first.items[0]).toMatchObject({outcome:'committed-needs-attention',retryable:true});const retry=await updates.apply(plan.id,'a');expect(retry.items[0].outcome).toBe('updated');expect(e.apply).toHaveBeenCalledOnce();expect(e.reconcile).toHaveBeenCalledOnce();+ });+ it('rechecks activity before child apply and retains the prior committed outcome', async () => {+ const a=entry('a'),b=entry('b');const {updates,idle}=fixture([a,b]);a.apply=vi.fn(async()=>{idle.mockImplementation(()=>{throw Error('closing');});return {committed:true};});const plan=await updates.plan(),r=await updates.apply(plan.id);expect(r.items[0].committed).toBe(true);expect(r.items[1].outcome).toBe('failed-before-commit');expect(b.apply).not.toHaveBeenCalled();+ });+ it('releases admission if progress notification throws', async () => {+ let fail=false;const {updates,admission}=fixture([entry('a')],()=>{if(fail)throw Error('notification');});const plan=await updates.plan();fail=true;await expect(updates.apply(plan.id)).rejects.toThrow('notification');expect(admission.busy).toBe(false);+ });+ it('hides stale plan and retry results after context changes, including remount reads', async () => {+ let context='A';const admission=new ComponentUpdateAdmission(()=>{}),e=entry('a');+ const updates=new ComponentUpdates(admission,async()=>[e],()=>{},()=>false,()=>context);+ const plan=await updates.plan();await updates.apply(plan.id);expect(updates.current.result).toBeDefined();context='B';+ expect(updates.current).toEqual({running:false});await expect(updates.apply(plan.id)).rejects.toThrow('context');expect(e.apply).toHaveBeenCalledOnce();+ });+ it('rejects unknown plans, nonretryable items and repeated application without work', async () => {+ const e=entry('a');const {updates,admission}=fixture([e]);await expect(updates.apply('foreign')).rejects.toThrow('stale');expect(admission.busy).toBe(false);const plan=await updates.plan();await updates.apply(plan.id);await expect(updates.apply(plan.id)).rejects.toThrow('already');await expect(updates.apply(plan.id,'a')).rejects.toThrow('cannot');expect(e.apply).toHaveBeenCalledOnce();+ });+});diff --git a/src/main/component-updates.ts b/src/main/component-updates.tsnew file mode 100644index 0000000..4aae72e--- /dev/null+++ b/src/main/component-updates.ts@@ -0,0 +1,109 @@+import { randomUUID } from 'node:crypto';+import type { ComponentUpdateBatchResult, ComponentUpdateItemResult, ComponentUpdatePlan, ComponentUpdatePlanItem, ComponentUpdatesStatus } from '../shared/types.js';+import { ComponentUpdateAdmission, type ComponentUpdateOwner } from './component-update-admission.js';+export interface PreparedComponentUpdate {+ readonly item: ComponentUpdatePlanItem;+ /** Compare installed identity and context, never silently substitute latest. */+ isCurrent(): Promise<boolean>;+ apply(owner: ComponentUpdateOwner): Promise<{ committed: boolean; restartRequired?: boolean }>;+ /** Postcommit retry must only reconcile existing activation, not install again. */+ reconcile?(owner: ComponentUpdateOwner): Promise<{ restartRequired?: boolean }>;+}+export interface ComponentUpdateFailure extends Error { committed?: boolean }+export class ComponentUpdates {+ private prepared: PreparedComponentUpdate[] = [];+ private state: ComponentUpdatesStatus = { running: false };+ private generation = 0;+ private context?: string;+ constructor(private readonly admission: ComponentUpdateAdmission,+ private readonly discover: () => Promise<PreparedComponentUpdate[]>,+ private readonly changed: () => void,+ private readonly restartPending: () => boolean,+ private readonly currentContext: () => string = () => '') {}+ get current(): ComponentUpdatesStatus {+ if (this.context !== undefined && this.context !== this.currentContext()) return { running: this.state.running };+ return structuredClone(this.state);+ }+ async plan(): Promise<ComponentUpdatePlan> {+ this.admission.assertAllowed();+ const generation = ++this.generation;+ const context = this.currentContext();+ const prepared = await this.discover();+ this.admission.assertAllowed();+ if (context !== this.currentContext()) throw Error('The component update context changed. Check again.');+ if (generation !== this.generation) throw Error('A newer component update check replaced this plan.');+ const ids = new Set<string>();+ for (const entry of prepared) {+ if (!entry.item.id || ids.has(entry.item.id)) throw Error('Duplicate component update identity.');+ ids.add(entry.item.id);+ }+ // Launcher last, stable order within the runtime family set.+ const rank = { backend: 0, runtime: 1, launcher: 2 };+ this.prepared = [...prepared].sort((a, b) => rank[a.item.component] - rank[b.item.component]);+ const plan: ComponentUpdatePlan = { id: randomUUID(), createdAt: new Date().toISOString(), items: this.prepared.map(row => structuredClone(row.item)) };+ this.context = context;+ this.state = { running: false, plan };+ this.changed();+ return structuredClone(plan);+ }+ async apply(planId: string, retryItemId?: string): Promise<ComponentUpdateBatchResult> {+ // Synchronous reservation closes the first-await window for all child operations.+ const owner = this.admission.reserve();+ try {+ if (!this.state.plan || typeof planId !== 'string' || planId !== this.state.plan.id) throw Error('The component update plan is stale. Check again.');+ if (this.context !== this.currentContext()) throw Error('The component update context changed. Check again.');+ const previous = this.state.result;+ if (retryItemId !== undefined && (!previous || !previous.items.some(row => row.id === retryItemId && row.retryable))) throw Error('This component cannot be retried.');+ if (retryItemId === undefined && previous) throw Error('This plan was already executed. Retry an eligible component or check again.');+ const results: ComponentUpdateItemResult[] = retryItemId ? structuredClone(previous!.items) : [];+ this.state.running = true;+ this.changed();+ let stopped = false;+ for (const entry of this.prepared) {+ if (retryItemId && entry.item.id !== retryItemId) continue;+ let result: ComponentUpdateItemResult;+ const old = previous?.items.find(row => row.id === entry.item.id);+ if (stopped) result = { id: entry.item.id, outcome: 'not-run', committed: false, retryable: false, message: 'An earlier component needs attention.' };+ else if (entry.item.state !== 'ready') result = { id: entry.item.id, outcome: entry.item.state, committed: false, retryable: false, message: entry.item.reason };+ else {+ this.state.phase = entry.item.label;+ this.changed();+ try {+ this.admission.assertActivity(owner);+ if (this.context !== this.currentContext()) throw Error('The component update context changed. Check again.');+ // A committed retry compares the captured target in its reconcile adapter.+ if (old?.committed) {+ if (!entry.reconcile) throw Object.assign(Error('Activation needs manual reconciliation.'), { committed: true });+ await entry.reconcile(owner);+ result = { id: entry.item.id, outcome: 'updated', committed: true, retryable: false };+ } else if (!await entry.isCurrent()) {+ result = { id: entry.item.id, outcome: 'stale', committed: false, retryable: false, message: 'The installed component or update context changed. Check again.' };+ stopped = true;+ } else {+ this.admission.assertActivity(owner);+ if (this.context !== this.currentContext()) throw Error('The component update context changed. Check again.');+ const applied = await entry.apply(owner);+ result = { id: entry.item.id, outcome: 'updated', committed: applied.committed, retryable: false };+ }+ } catch (error) {+ const committed = old?.committed === true || (error as ComponentUpdateFailure)?.committed === true;+ result = { id: entry.item.id, outcome: committed ? 'committed-needs-attention' : 'failed-before-commit', committed,+ retryable: committed ? Boolean(entry.reconcile) : true, message: error instanceof Error ? error.message : String(error) };+ stopped = true;+ }+ }+ const index = results.findIndex(row => row.id === result.id);+ if (index < 0) results.push(result); else results[index] = result;+ this.state.result = { planId, items: structuredClone(results), restartRequired: this.restartPending() };+ this.changed();+ }+ this.state.result = { planId, items: results, restartRequired: this.restartPending() };+ return structuredClone(this.state.result);+ } finally {+ this.state.running = false;+ this.state.phase = undefined;+ this.admission.release(owner);+ this.changed();+ }+ }+}