Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: preserve forge scope repair during combined app updates (#13234)
Adam Eivy58d99d7f9590
diff --git a/client/src/components/apps/tabs/RepositorySourcePanel.jsx b/client/src/components/apps/tabs/RepositorySourcePanel.jsxindex 540030b2ba..6d6d391eac 100644--- a/client/src/components/apps/tabs/RepositorySourcePanel.jsx+++ b/client/src/components/apps/tabs/RepositorySourcePanel.jsx@@ -194,10 +194,24 @@ export default function RepositorySourcePanel({ appId, appName, onUpdated, refreoperationType,error: operationError,errorCode: operationErrorCode,+ errorContext: operationErrorContext,completed: operationCompleted,restarting,startUpdate,} = useAppOperation({ appId, onComplete: handleOperationComplete });+ useEffect(() => {+ setUpdateRequested(false);+ setScopeFailure(null);+ }, [appId]);++ useEffect(() => {+ const failure = forgeScopeFailureFrom({ code: operationErrorCode, context: operationErrorContext, message: operationError });+ if (!failure) return;+ setScopeFailure(failure);+ // Fork sync refused before the checkout update began; an explicit retry is safe.+ setUpdateRequested(false);+ }, [operationErrorCode, operationErrorContext, operationError]);+const updating = isOperating && operationType === 'update';const operationBusy = isOperating || restarting;@@ -205,10 +219,6 @@ export default function RepositorySourcePanel({ appId, appName, onUpdated, refreif (updating) setUpdateRequested(true);}, [updating]);- useEffect(() => {- setUpdateRequested(false);- }, [appId]);-useEffect(() => {load({ initial: true });}, [load]);@@ -266,6 +276,7 @@ export default function RepositorySourcePanel({ appId, appName, onUpdated, refre}const intent = updateIntent;setUpdateIntent(null);+ setScopeFailure(null);setUpdateRequested(true);startUpdate(appId, appName, { syncFork: intent?.syncFork === true });};@@ -310,7 +321,7 @@ export default function RepositorySourcePanel({ appId, appName, onUpdated, refreonDismiss={() => setScopeFailure(null)}onRefreshed={() => {setScopeFailure(null);- toast('Token updated — sync the fork again');+ toast('Token updated — retry the original action');}}/></div>diff --git a/client/src/components/apps/tabs/RepositorySourcePanel.test.jsx b/client/src/components/apps/tabs/RepositorySourcePanel.test.jsxindex c0b2d97ec4..79a324ef74 100644--- a/client/src/components/apps/tabs/RepositorySourcePanel.test.jsx+++ b/client/src/components/apps/tabs/RepositorySourcePanel.test.jsx@@ -15,13 +15,14 @@ vi.mock('../../../services/apiLocalLlm', async (importOriginal) => ({getToolUseModels: vi.fn().mockResolvedValue({ models: [] }),}));vi.mock('../../../hooks/useForgeScopeRefresh', () => ({- default: () => ({ active: false, pending: false, device: null, start: vi.fn(), cancel: vi.fn() }),+ default: vi.fn(() => ({ active: false, pending: false, device: null, start: vi.fn(), cancel: vi.fn() })),}));vi.mock('../../../hooks/useAppOperation', () => ({useAppOperation: vi.fn(),}));import * as api from '../../../services/api';+import useForgeScopeRefresh from '../../../hooks/useForgeScopeRefresh';import { useAppOperation } from '../../../hooks/useAppOperation';import RepositorySourcePanel from './RepositorySourcePanel';import { MemoryRouter } from 'react-router';@@ -189,6 +190,46 @@ describe('managed app repository sources', () => {expect(screen.getByRole('button', { name: /Authorize workflow/ })).toBeInTheDocument();});+ it.each([+ { credential: 'oauth', command: 'gh auth refresh -h ghe.example.com -s workflow', refreshable: true },+ { credential: 'personal-access-token', command: null, refreshable: false },+ { credential: 'oauth', command: 'gh auth refresh -h ghe.example.com -s workflow', refreshable: false },+ ])('repairs a combined update scope refusal without automatically retrying ($credential, $refreshable)', async (guidance) => {+ const status = canonicalStatus();+ status.sources[0].origin = { ...status.sources[0].origin, isFork: true, isUpstream: false };+ status.sources[0].forkVsUpstream = { available: true, ahead: 0, behind: 2, state: 'behind' };+ status.sources[0].forkSyncable = true;+ api.getAppRepositorySources.mockResolvedValue(status);+ const startUpdate = vi.fn();+ const operation = { steps: [], isOperating: false, operationType: 'update', startUpdate };+ useAppOperation.mockImplementation(() => operation);+ const view = render(<RepositorySourcePanel appId="app-example" appName="Example App" />);+ fireEvent.click(await screen.findByRole('button', { name: 'Sync fork & update app' }));+ fireEvent.click(await screen.findByRole('button', { name: 'Sync fork and update' }));+ expect(screen.getByRole('button', { name: 'Reload to update again' })).toBeDisabled();++ Object.assign(operation, { error: 'workflow scope missing', errorCode: 'FORGE_TOKEN_SCOPE_MISSING',+ errorContext: { host: 'ghe.example.com', scopes: ['workflow'], ...guidance } });+ view.rerender(<RepositorySourcePanel appId="app-example" appName="Example App" />);+ expect(await screen.findByText(/ghe\.example\.com token is missing the workflow scope/)).toBeInTheDocument();+ expect(screen.getByRole('button', { name: 'Sync fork & update app' })).toBeEnabled();+ if (guidance.refreshable) {+ const authorize = screen.getByRole('button', { name: 'Authorize workflow' });+ fireEvent.click(authorize);+ expect(useForgeScopeRefresh.mock.results.at(-1).value.start).toHaveBeenCalledWith(['workflow']);+ act(() => useForgeScopeRefresh.mock.calls.at(-1)[0].onRefreshed());+ expect(screen.queryByRole('button', { name: 'Authorize workflow' })).not.toBeInTheDocument();+ } else {+ expect(screen.queryByRole('button', { name: 'Authorize workflow' })).not.toBeInTheDocument();+ expect(guidance.command ? screen.getByText(guidance.command) : screen.getByText(/personal access token, which can't be updated/)).toBeInTheDocument();+ }+ expect(startUpdate).toHaveBeenCalledTimes(1);+ fireEvent.click(screen.getByRole('button', { name: 'Sync fork & update app' }));+ fireEvent.click(await screen.findByRole('button', { name: 'Sync fork and update' }));+ expect(startUpdate).toHaveBeenLastCalledWith('app-example', 'Example App', { syncFork: true });+ expect(startUpdate).toHaveBeenCalledTimes(2);+ });+// Eidoverse's video checkout is cloned from `anima-research`'s fork of a third// project. The drift from upstream is real and worth reporting, but PortOS can// only read that fork — so the panel must say so instead of offering a syncdiff --git a/client/src/hooks/useAppOperation.js b/client/src/hooks/useAppOperation.jsindex 2f6d02296c..b14a258db2 100644--- a/client/src/hooks/useAppOperation.js+++ b/client/src/hooks/useAppOperation.js@@ -99,6 +99,7 @@ export function useAppOperation({ onComplete, appId: scopeAppId } = {}) {steps: op.steps?.length ? op.steps : (current?.steps || []),error: null,errorCode: null,+ errorContext: null,completed: false};}@@ -134,7 +135,7 @@ export function useAppOperation({ onComplete, appId: scopeAppId } = {}) {socket.emit('app:operations:list');return;}- patch(data, current => ({ ...current, error: data?.message || 'Operation failed', errorCode: data?.code || null }));+ patch(data, current => ({ ...current, error: data?.message || 'Operation failed', errorCode: data?.code || null, errorContext: data?.code === 'FORGE_TOKEN_SCOPE_MISSING' ? data.context ?? null : null }));};const onDone = (data) => {@@ -195,7 +196,7 @@ export function useAppOperation({ onComplete, appId: scopeAppId } = {}) {const start = useCallback((type, appId, appName, options = {}) => {clearTimeout(clearTimersRef.current[appId]);delete clearTimersRef.current[appId];- setOperations(prev => ({ ...prev, [appId]: { appId, appName, type, steps: [], error: null, errorCode: null, completed: false } }));+ setOperations(prev => ({ ...prev, [appId]: { appId, appName, type, steps: [], error: null, errorCode: null, errorContext: null, completed: false } }));// Record the running server's version and uptime while it can still answer —// the restart watch compares against them. Deliberately NOT awaited: nothing// reads the baseline for at least a second, and blocking the dispatch on a@@ -223,6 +224,7 @@ export function useAppOperation({ onComplete, appId: scopeAppId } = {}) {steps: primary?.steps || [],error: primary?.error ?? null,errorCode: primary?.errorCode ?? null,+ errorContext: primary?.errorContext ?? null,completed: primary?.completed ?? false,operatingAppId: primary?.appId ?? null,operatingAppName: primary?.appName ?? null,diff --git a/client/src/hooks/useAppOperation.test.jsx b/client/src/hooks/useAppOperation.test.jsxindex a04cd0032c..9820b76edc 100644--- a/client/src/hooks/useAppOperation.test.jsx+++ b/client/src/hooks/useAppOperation.test.jsx@@ -44,6 +44,23 @@ describe('useAppOperation — PortOS self-update handoff', () => {afterEach(() => { vi.useRealTimers(); });+ it('retains scope repair after the failed operation leaves the active set and clears it on retry', () => {+ const { result } = renderHook(() => useAppOperation({ appId: 'app-example' }));+ const context = { host: 'ghe.example.com', scopes: ['workflow'], command: 'gh auth refresh -h ghe.example.com -s workflow', refreshable: true };+ act(() => {+ result.current.startUpdate('app-example', 'Example', { syncFork: true });+ socketHandlers.get('app:update:step')({ appId: 'app-example', step: 'fork-sync', status: 'running', message: 'Syncing fork' });+ socketHandlers.get('app:update:error')({ appId: 'app-example', code: 'FORGE_TOKEN_SCOPE_MISSING', message: 'scope missing', context });+ socketHandlers.get('app:operations:active')({ operations: [] });+ });+ expect(result.current).toMatchObject({ isOperating: false, errorCode: 'FORGE_TOKEN_SCOPE_MISSING', errorContext: context });+ expect(result.current.steps).toEqual([expect.objectContaining({ step: 'fork-sync' })]);+ act(() => result.current.startUpdate('app-example', 'Example', { syncFork: true }));+ expect(result.current.errorContext).toBeNull();+ act(() => socketHandlers.get('app:update:error')({ appId: 'app-example', message: 'generic failure', context }));+ expect(result.current.errorContext).toBeNull();+ });+it('records the running version before dispatching, without blocking the emit', () => {const { result } = renderHook(() => useAppOperation({ appId: PORTOS_APP_ID }));diff --git a/server/lib/README.md b/server/lib/README.mdindex 917faa879b..cfa4227d8d 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -21,6 +21,8 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub## Validation (Zod schemas + request validators)+| `appOperationErrorContext.js` | `appOperationErrorContext` projects bounded forge scope repair fields for failed update events and history; all other error context is withheld. |+`managedVisitorValidation.js` — strict scoped managed-visitor credentials, admissions, observations and bounded action schemas.| Module | Purpose |diff --git a/server/lib/appOperationErrorContext.js b/server/lib/appOperationErrorContext.jsnew file mode 100644index 0000000000..05013aee8f--- /dev/null+++ b/server/lib/appOperationErrorContext.js@@ -0,0 +1,16 @@+/** Bounded repair guidance only; arbitrary provider/error context stays server-side. */+export const appOperationErrorContext = (error) => {+ const context = error?.context;+ if (error?.code !== 'FORGE_TOKEN_SCOPE_MISSING' || !context+ || typeof context.host !== 'string' || !/^[a-z0-9][a-z0-9.-]{0,252}$/i.test(context.host)+ || !Array.isArray(context.scopes) || context.scopes.length === 0 || context.scopes.length > 16+ || !context.scopes.every(scope => typeof scope === 'string' && /^[a-z0-9:_-]{1,64}$/i.test(scope))+ || (context.command != null && (typeof context.command !== 'string' || context.command.length > 1024))) return null;+ return {+ host: context.host,+ scopes: [...context.scopes],+ command: context.command ?? null,+ ...(context.credential === 'oauth' || context.credential === 'personal-access-token' ? { credential: context.credential } : {}),+ refreshable: context.refreshable === true,+ };+};diff --git a/server/lib/index.js b/server/lib/index.jsindex 0dbd896eac..65ef0ac306 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -16,6 +16,7 @@// brain and digital-twin) can be disambiguated as `brainValidation.X` /// `digitalTwinValidation.X`. The catch-all `validation.js` stays flat — its// names are the canonical PortOS-wide schemas.+export * from './appOperationErrorContext.js';export * from './appPromptPlaceholders.js';export * from './appDeployFlags.js';export * from './apiContractSchemas.js';diff --git a/server/services/appUpdateRunner.js b/server/services/appUpdateRunner.jsindex d2e1d6ffa6..6fbb991d4d 100644--- a/server/services/appUpdateRunner.js+++ b/server/services/appUpdateRunner.js@@ -19,6 +19,7 @@ import * as appUpdater from './appUpdater.js';import { logAction } from './history.js';import { checkPortosUpdatePreflight } from './updatePreflight.js';import { claimAppOperation, endAppOperation, recordOperationStep } from './appOperations.js';+import { appOperationErrorContext } from '../lib/appOperationErrorContext.js';import { PORTOS_APP_ID } from '../lib/appIdentity.js';/**@@ -91,24 +92,29 @@ export async function runAppUpdate({};let failure = null;+ let errorContext = null;result = await appUpdater.updateApp(app, emit, {syncFork,acknowledgeFork,acknowledgePersistentMindImageBackup,}).catch(err => {failure = err;+ errorContext = appOperationErrorContext(err);// Refusals raised inside the update (the PortOS launcher's post-lock// re-check, say) carry the same acknowledgement codes the pre-check// emits above — the panel's retry buttons key on `code`, so dropping it// here would leave a refusal the user could have acted on inert.- io.emit('app:update:error', { appId: app.id, code: err.code || null, message: err.message });+ io.emit('app:update:error', { appId: app.id, code: err.code || null, message: err.message, ...(errorContext ? { context: errorContext } : {}) });return null;});// The ledger and the apps-changed broadcast belong to this path now that it// is the only way to update an app — a thrown update still gets a row, with// success:false, rather than vanishing from the history.- await logAction('update', app.id, app.name, { steps: result?.steps ?? [] }, result?.success === true, failure?.message ?? null);+ await logAction('update', app.id, app.name, {+ steps: result?.steps ?? operation.steps,+ ...(errorContext ? { errorCode: failure.code, errorContext } : {}),+ }, result?.success === true, failure?.message ?? null);appsService.notifyAppsChanged('update', app.id);if (result?.selfUpdateStarted) {diff --git a/server/sockets/apps.test.js b/server/sockets/apps.test.jsindex bb07bb64d7..06cc408962 100644--- a/server/sockets/apps.test.js+++ b/server/sockets/apps.test.js@@ -327,7 +327,7 @@ describe('app socket handlers', () => {describe('failure recovery', () => {it('records a failed update in the ledger, broadcasts the change, and clears the operation', async () => {- appUpdater.updateApp.mockRejectedValue(new Error('git pull failed'));+ appUpdater.updateApp.mockRejectedValue(Object.assign(new Error('git pull failed'), { context: { token: 'do-not-export' } }));const client = connect(bus);await client.fire('app:update', { appId: 'app-a' });@@ -343,6 +343,45 @@ describe('app socket handlers', () => {expect(client.last('app:operations:active').payload.operations).toEqual([]);});+ it.each([+ { credential: 'oauth', command: 'gh auth refresh -h ghe.example.com -s workflow', refreshable: true },+ { credential: 'personal-access-token', command: null, refreshable: false },+ { credential: 'oauth', command: 'gh auth refresh -h ghe.example.com -s workflow', refreshable: false },+ ])('preserves bounded scope repair and progress for a refused combined update ($credential, $refreshable)', async (guidance) => {+ const context = { host: 'ghe.example.com', scopes: ['workflow'], ...guidance };+ appUpdater.updateApp.mockImplementation(async (_app, emit) => {+ emit('fork-sync', 'running', 'Syncing fork');+ throw Object.assign(new Error('workflow scope missing'), {+ code: 'FORGE_TOKEN_SCOPE_MISSING', context: { ...context, token: 'do-not-export', raw: { private: true } },+ });+ });+ const client = connect(bus);+ await client.fire('app:update', { appId: 'app-a', syncFork: true });+ expect(appUpdater.updateApp).toHaveBeenCalledWith(APPS['app-a'], expect.any(Function), expect.objectContaining({ syncFork: true }));+ expect(client.last('app:update:error').payload).toEqual({+ appId: 'app-a', code: 'FORGE_TOKEN_SCOPE_MISSING', message: 'workflow scope missing', context,+ });+ expect(logAction).toHaveBeenCalledWith('update', 'app-a', 'Example App A', {+ steps: [expect.objectContaining({ step: 'fork-sync', message: 'Syncing fork' })],+ errorCode: 'FORGE_TOKEN_SCOPE_MISSING', errorContext: context,+ }, false, 'workflow scope missing');+ expect(client.events('app:update:complete')).toHaveLength(0);+ expect(client.last('app:operations:active').payload.operations).toEqual([]);+ });++ it('withholds malformed or oversized scope context from failed operation events and history', async () => {+ for (const context of [+ { host: 'ghe.example.com', scopes: 'workflow' },+ { host: 'ghe.example.com', scopes: ['workflow'], command: 'x'.repeat(1025) },+ ]) {+ appUpdater.updateApp.mockRejectedValue(Object.assign(new Error('scope missing'), { code: 'FORGE_TOKEN_SCOPE_MISSING', context }));+ const client = connect(bus);+ await client.fire('app:update', { appId: 'app-a', syncFork: true });+ expect(client.last('app:update:error').payload).toEqual({ appId: 'app-a', code: 'FORGE_TOKEN_SCOPE_MISSING', message: 'scope missing' });+ expect(logAction).toHaveBeenLastCalledWith('update', 'app-a', 'Example App A', { steps: [] }, false, 'scope missing');+ }+ });+it('surfaces a standardize analyze failure as an error step and never reaches apply', async () => {pm2Standardizer.analyzeApp.mockRejectedValue(new Error('LLM provider unavailable'));const client = connect(bus);