Skip to content

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

fix: address data safety and UI release review findings

[._.]/ Adam Eivyfe0d719c87bc
diff --git a/client/src/components/NotificationDropdown.jsx b/client/src/components/NotificationDropdown.jsx
index f3128eaf86..bb723b9caf 100644
--- a/client/src/components/NotificationDropdown.jsx
+++ b/client/src/components/NotificationDropdown.jsx
@@ -204,7 +204,7 @@ export default function NotificationDropdown({
type="button"
ref={closeRef}
onClick={() => setIsOpen(false)}
- className="inline-flex items-center justify-center min-w-[44px] min-h-[44px] rounded hover:bg-port-border transition-colors focus:outline-hidden focus:ring-2 focus:ring-port-accent sm:hidden"
+ className="inline-flex items-center justify-center min-w-[44px] min-h-[44px] rounded hover:bg-port-border transition-colors focus:outline-hidden focus:ring-2 focus:ring-port-accent sm:min-w-0 sm:min-h-0 sm:p-1.5"
title="Close"
aria-label="Close notifications"
>
diff --git a/client/src/components/NotificationDropdown.test.jsx b/client/src/components/NotificationDropdown.test.jsx
index 8a39d1991b..3b8caba571 100644
--- a/client/src/components/NotificationDropdown.test.jsx
+++ b/client/src/components/NotificationDropdown.test.jsx
@@ -161,7 +161,7 @@ describe('NotificationDropdown', () => {
}
});
- it('retains panel focus when updates remove the focused action', async () => {
+ it('retains desktop panel focus when updates remove the focused action', async () => {
const user = userEvent.setup();
function LiveDropdown() {
const [notifications, setNotifications] = useState(makeNotifications(2));
@@ -175,10 +175,15 @@ describe('NotificationDropdown', () => {
/>
);
}
- render(<MemoryRouter><LiveDropdown /></MemoryRouter>);
+ render(<MemoryRouter>
+ {/* Apply the desktop hiding rule: happy-dom does not load Tailwind's CSS. */}
+ <style>{'.sm\\:hidden { display: none; }'}</style>
+ <LiveDropdown />
+ </MemoryRouter>);
openPanel();
await user.keyboard('{Enter}');
const close = screen.getByRole('button', { name: 'Close notifications' });
+ expect(getComputedStyle(close).display).not.toBe('none');
expect(close).toHaveFocus();
await user.click(screen.getByRole('button', { name: 'Remove notification: Notification 0' }));
diff --git a/client/src/components/apps/tabs/PullRequestsTab.jsx b/client/src/components/apps/tabs/PullRequestsTab.jsx
index 5c15606565..6e45565462 100644
--- a/client/src/components/apps/tabs/PullRequestsTab.jsx
+++ b/client/src/components/apps/tabs/PullRequestsTab.jsx
@@ -502,11 +502,11 @@ export default function PullRequestsTab({ appId, appName }) {
if (actionStatus === 'failed') {
return (
<div key={kind} className="max-w-md text-xs text-port-error space-y-2" role="alert">
- <p>{action.error || 'PR review preflight failed before an agent started.'}</p>
+ <p>{action.error || (kind === 'review' ? 'PR review failed. View the failure record for details.' : 'Resolve & merge failed. View the failure record for details.')}</p>
<div className="flex flex-wrap gap-3">
<Link className="underline" to={`/cos/tasks?task=${encodeURIComponent(action.taskId)}&source=internal`}>View failure record</Link>
- <Link className="underline" to="/models/llms/abuse">Abuse Guard setup</Link>
- <button type="button" className="underline" onClick={() => onQueue(pullRequest)}>Retry PR review</button>
+ {kind === 'review' && <Link className="underline" to="/models/llms/abuse">Abuse Guard setup</Link>}
+ <button type="button" className="underline" onClick={() => onQueue(pullRequest)}>{kind === 'review' ? 'Retry PR review' : 'Retry resolve & merge'}</button>
</div>
</div>
);
diff --git a/client/src/components/apps/tabs/PullRequestsTab.test.jsx b/client/src/components/apps/tabs/PullRequestsTab.test.jsx
index 46524c7691..08229248f0 100644
--- a/client/src/components/apps/tabs/PullRequestsTab.test.jsx
+++ b/client/src/components/apps/tabs/PullRequestsTab.test.jsx
@@ -352,6 +352,24 @@ describe('PullRequestsTab', () => {
expect(await screen.findByRole('link', { name: /PR review: Queued/ })).toBeInTheDocument();
});
+ it('names a failed resolve retry as a merge action and retries that same action', async () => {
+ api.getAppPullRequests.mockResolvedValue(okPayload([{
+ ...PULL_REQUEST,
+ agentAction: { taskId: 'resolve-failed', status: 'failed' },
+ }]));
+ await renderTab();
+
+ expect(await screen.findByRole('alert')).toHaveTextContent('Resolve & merge failed');
+ expect(screen.queryByRole('link', { name: 'Abuse Guard setup' })).not.toBeInTheDocument();
+ expect(screen.queryByRole('button', { name: 'Retry PR review' })).not.toBeInTheDocument();
+ fireEvent.click(screen.getByRole('button', { name: 'Retry resolve & merge' }));
+ await waitFor(() => expect(api.resolveAppPullRequest).toHaveBeenCalledWith(
+ 'app-1', 17, { provider: undefined, model: undefined, effort: undefined },
+ ));
+ expect(api.reviewAppPullRequest).not.toHaveBeenCalled();
+ expect(await screen.findByRole('link', { name: /Resolve & merge: Queued/ })).toBeInTheDocument();
+ });
+
it('hydrates an in-flight pr-reviewer run without offering the button again', async () => {
api.getAppPullRequests.mockResolvedValue(okPayload([{
...PULL_REQUEST,
diff --git a/client/src/pages/ApiExplorer.jsx b/client/src/pages/ApiExplorer.jsx
index 774308f1bc..6b1207bda0 100644
--- a/client/src/pages/ApiExplorer.jsx
+++ b/client/src/pages/ApiExplorer.jsx
@@ -188,10 +188,14 @@ function RestReferenceView() {
const specPath = surface === 'internal' ? '/api/api-docs/internal/openapi.json' : '/api/api-docs/openapi.json';
useEffect(() => {
+ let cancelled = false;
const load = surface === 'internal' ? api.getInternalOpenApiSpec : api.getOpenApiSpec;
setSpec(null);
setError('');
- load({ silent: true }).then(setSpec).catch((err) => setError(err.message));
+ load({ silent: true })
+ .then((value) => { if (!cancelled) setSpec(value); })
+ .catch((err) => { if (!cancelled) setError(err.message); });
+ return () => { cancelled = true; };
}, [surface]);
const operations = useMemo(() => operationsFromOpenApi(spec), [spec]);
diff --git a/client/src/pages/ApiExplorer.test.jsx b/client/src/pages/ApiExplorer.test.jsx
index d7bb41bb8f..64be8f1173 100644
--- a/client/src/pages/ApiExplorer.test.jsx
+++ b/client/src/pages/ApiExplorer.test.jsx
@@ -1,5 +1,5 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
-import { fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';
import { MemoryRouter, Route, Routes } from 'react-router';
const api = vi.hoisted(() => ({
@@ -128,6 +128,29 @@ describe('ApiExplorer', () => {
expect(screen.getByText('CoS Agent MCP')).toBeTruthy();
});
+ it('keeps the current REST surface when earlier reads succeed or fail late', async () => {
+ let finishInternal;
+ let failPublic;
+ api.getInternalOpenApiSpec.mockImplementationOnce(() => new Promise(resolve => { finishInternal = resolve; }));
+ renderPage('/api-reference/rest');
+ fireEvent.click(screen.getByRole('button', { name: 'Exposed' }));
+ await screen.findByText('/api/voice/public/synthesize');
+ await act(async () => { finishInternal(internalSpec); });
+ expect(screen.queryByText('/api/apps')).not.toBeInTheDocument();
+ expect(screen.getByText('/api/voice/public/synthesize')).toBeInTheDocument();
+
+ fireEvent.click(screen.getByRole('button', { name: 'Internal' }));
+ await screen.findByText('/api/apps');
+ api.getOpenApiSpec.mockImplementationOnce(() => new Promise((_resolve, reject) => { failPublic = reject; }));
+ fireEvent.click(screen.getByRole('button', { name: 'Exposed' }));
+ fireEvent.click(screen.getByRole('button', { name: 'Internal' }));
+ await screen.findByText('/api/apps');
+ await act(async () => { failPublic(new Error('Old public request failed')); });
+ expect(screen.getByText('/api/apps')).toBeInTheDocument();
+ expect(screen.queryByText(/OpenAPI spec unavailable/)).not.toBeInTheDocument();
+ expect(screen.getByRole('link', { name: /Open JSON/i })).toHaveAttribute('href', '/api/api-docs/internal/openapi.json');
+ });
+
it('renders the generated Socket.IO catalog and AsyncAPI link', async () => {
renderPage('/api-reference/events');
expect(await screen.findByText('229')).toBeTruthy();
diff --git a/client/src/pages/MediaCollections.jsx b/client/src/pages/MediaCollections.jsx
index 981ad5789b..bc1ad87145 100644
--- a/client/src/pages/MediaCollections.jsx
+++ b/client/src/pages/MediaCollections.jsx
@@ -106,10 +106,17 @@ export default function MediaCollections() {
const handleDelete = async (collection) => {
setCollections((prev) => (prev ? prev.filter((c) => c.id !== collection.id) : prev));
- await deleteMediaCollection(collection.id, { silent: true }).catch((err) => {
+ const deleted = await deleteMediaCollection(collection.id, { silent: true }).then(() => true).catch((err) => {
toast.error(err.message || 'Delete failed');
refresh();
+ return false;
});
+ if (!deleted) return;
+ // Removing the last membership makes its media Unsorted. Counts and covers
+ // are server-owned now, so update that projection after the delete commits.
+ const nextSummaries = await listGalleryCollectionSummaries({ silent: true }).catch(() => null);
+ if (nextSummaries) setSummaries(nextSummaries);
+ else setCollectionsError('Could not load collection covers and counts.');
};
const unsorted = useMemo(() => ({ ...buildUnsortedCollection([], [], []),
diff --git a/client/src/pages/MediaCollections.test.jsx b/client/src/pages/MediaCollections.test.jsx
index 8d75adf83b..b1d64974ea 100644
--- a/client/src/pages/MediaCollections.test.jsx
+++ b/client/src/pages/MediaCollections.test.jsx
@@ -332,4 +332,29 @@ describe('MediaCollections', () => {
expect([...select.options].map((o) => o.textContent))
.toEqual(['Recently updated', 'Name', 'Item count']);
});
+
+ it('reveals newly unfiled images after deleting their only collection', async () => {
+ const { listMediaCollections, listGalleryCollectionSummaries, deleteMediaCollection } = await import('../services/api');
+ mockUnsortedItems = [];
+ listMediaCollections.mockResolvedValueOnce([
+ { id: 'col-1', name: 'Alpha', items: [{ kind: 'image', ref: 'img1.png' }] },
+ ]);
+ listGalleryCollectionSummaries.mockResolvedValueOnce([
+ { id: 'unsorted', total: 0, counts: { image: 0, video: 0 }, cover: null },
+ { id: 'col-1', total: 1, counts: { image: 1, video: 0 }, cover: '/data/images/img1.png' },
+ ]).mockResolvedValueOnce([
+ { id: 'unsorted', total: 1, counts: { image: 1, video: 0 }, cover: '/data/images/img1.png' },
+ ]);
+ deleteMediaCollection.mockResolvedValueOnce({ id: 'col-1' });
+ const user = userEvent.setup();
+ renderPage();
+ await screen.findByText('Alpha');
+ expect(screen.queryByText('Unsorted')).not.toBeInTheDocument();
+ await user.click(screen.getByRole('button', { name: 'Delete collection' }));
+ const unsorted = await screen.findByTitle('Unsorted');
+ expect(unsorted).toHaveAttribute('href', '/media/collections/unsorted');
+ expect(screen.queryByText('Alpha')).not.toBeInTheDocument();
+ expect(within(unsorted.closest('.bg-port-card')).getByText('1')).toBeInTheDocument();
+ expect(listMediaCollections).toHaveBeenCalledTimes(1);
+ });
});
diff --git a/client/src/pages/VideoGen.jsx b/client/src/pages/VideoGen.jsx
index 7b57665332..424dde8218 100644
--- a/client/src/pages/VideoGen.jsx
+++ b/client/src/pages/VideoGen.jsx
@@ -1360,6 +1360,21 @@ export default function VideoGen() {
{optionsBlockReason && (
<span className="basis-full text-xs text-port-warning" role="status">{optionsBlockReason}</span>
)}
+ {/* Said BEFORE the button is pressed, not after the screen is already
+ dark. A user who first learns about the sleep by watching their
+ display go black reads it as a crash and wakes it — which puts
+ WindowServer back in contention with Metal and risks the GPU
+ watchdog panic the sleep exists to avoid. */}
+ {rendersSleepDisplay && !generating && (
+ <p className="flex items-start gap-1.5 text-[11px] text-port-warning">
+ <MonitorOff className="w-3.5 h-3.5 mt-px shrink-0" />
+ <span>
+ This render will put your display to sleep. The screen will go dark shortly
+ after you start — that is expected, and waking it can crash the render. Uncheck
+ “Sleep display during this render” in Options to keep the screen on.
+ </span>
+ </p>
+ )}
{progressPct != null && <span className="text-xs text-port-accent">{progressPct}%</span>}
{(generating || error) && (
<span className={`text-xs truncate ${error ? 'text-port-error' : 'text-gray-400'}`}>
@@ -1820,21 +1835,6 @@ export default function VideoGen() {
</label>
)}
- {/* Said BEFORE the button is pressed, not after the screen is already
- dark. A user who first learns about the sleep by watching their
- display go black reads it as a crash and wakes it — which puts
- WindowServer back in contention with Metal and risks the GPU
- watchdog panic the sleep exists to avoid. */}
- {rendersSleepDisplay && !generating && (
- <p className="flex items-start gap-1.5 text-[11px] text-port-warning">
- <MonitorOff className="w-3.5 h-3.5 mt-px shrink-0" />
- <span>
- This render will put your display to sleep. The screen will go dark shortly
- after you start — that is expected, and waking it can crash the render. Uncheck
- the option above if you would rather keep the screen on.
- </span>
- </p>
- )}
</div>
</details>
</div>
diff --git a/client/src/pages/VideoGen.primaryActions.test.jsx b/client/src/pages/VideoGen.primaryActions.test.jsx
index db94f50f10..f33ed6a6df 100644
--- a/client/src/pages/VideoGen.primaryActions.test.jsx
+++ b/client/src/pages/VideoGen.primaryActions.test.jsx
@@ -51,6 +51,19 @@ describe('VideoGen primary actions', () => {
expect(generate.compareDocumentPosition(options) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
});
+ it('warns before submitting a display-sleep render with mobile Options closed', async () => {
+ const sleepModel = videoGenModel('sleep-model', { sleepsDisplayDuringRender: true });
+ state.getVideoGenStatus.mockResolvedValue(videoGenStatus([sleepModel], { displaySleepOnRender: true }));
+ state.getVideoGenModelContext.mockResolvedValue(videoGenModelContext([sleepModel]));
+ await renderVideoGenPage();
+
+ const warning = await screen.findByText(/This render will put your display to sleep/);
+ const options = screen.getByText('Options').closest('details');
+ expect(options).not.toHaveAttribute('open');
+ expect(options).not.toContainElement(warning);
+ expect(screen.getByTestId('video-primary-actions')).toContainElement(warning);
+ });
+
it('uses the same primary action bar for every video mode', async () => {
await renderVideoGenPage();
await waitFor(() => expect(screen.getByLabelText('Model')).toHaveValue(MODEL.id));
diff --git a/docs/STORAGE.md b/docs/STORAGE.md
index 884e9e0581..a0ca9c4947 100644
--- a/docs/STORAGE.md
+++ b/docs/STORAGE.md
@@ -391,7 +391,7 @@ NOT EXISTS` in boot schema and init-db.sql provisions both existing and new
installs without transforming existing records. No seed or backfill fabricates
scores. The mandatory Postgres backup includes the table. Assessment rows and their prose remain machine-local. The PortOS baseline app
also exposes a numeric-only projection through `GET /api/apps/quality-federation`
-(`days=30|90|365`), gated on an identified, registered, enabled full-sync peer
+(`days=30|90|365`), gated on an identified, registered peer with sync enabled
with outbound sharing allowed. The ordinary app list and capability/status
payloads still carry no assessment data. See [quality federation](decisions/2026-09-10-portos-quality-federation.md).
diff --git a/docs/features/product-surfaces.md b/docs/features/product-surfaces.md
index 1353afb715..2c4ac99fad 100644
--- a/docs/features/product-surfaces.md
+++ b/docs/features/product-surfaces.md
@@ -182,7 +182,7 @@ Unified communication channels, local voice assistant, community stewardship, an
| **Stacker News Stewardship** | `/stacker-news` | Community territory moderation, Bitcoin Lightning tipping, post review, and encrypted credential storage. | [Stacker News](./stacker-news.md) |
| **OpenClaw Operator Chat** | `/openclaw` | Real-time interactive operator agent runtime with streaming sessions and persistent execution. | [OpenClaw Operator Chat](./openclaw-operator-chat.md) |
| **Evergreen Personal Wiki** | `/wiki/*` | Curated personal knowledge base with markdown editing, link graphs, and full-text search. | — |
-| **Voice Mode** | `/settings/voice` | Hands-free voice assistant with continuous VAD (AudioWorklet), speech-to-text (Whisper local or Web Speech), local LLM orchestration, text-to-speech (Kokoro-82M in-process or Piper), barge-in support, and `ui_navigate` tool execution. | [Voice Mode](./voice.md) |
+| **Voice Mode** | `/settings/voice` | Hands-free voice assistant with continuous VAD (AudioWorklet), speech-to-text (Whisper local or Web Speech), local LLM orchestration, text-to-speech (Piper or Qwen3-TTS), barge-in support, and `ui_navigate` tool execution. | [Voice Mode](./voice.md) |
| **Ambient Display Mode** | `/ambient` | Fullscreen idle dashboard, ambient animations, system status ticker, and display screensaver. | — |
| **Eidoverse Worlds** | `/eidoverse` | Private, install-local 3D world for the human and Persistent Mind/CoS agents, with durable name-based identity, world history, deterministic PortOS resource projection, and governed world augmentation. | [Eidoverse Worlds](./eidoverse.md) |
| **OpenWorld (retired compatibility surface)** | `/openworld`, `/city` | Historical Three.js / React Three Fiber world; legacy routes redirect to Eidoverse so existing bookmarks remain usable. | [OpenWorld](./openworld.md) |
diff --git a/server/lib/agentValidation.js b/server/lib/agentValidation.js
index 37edde5129..8344875319 100644
--- a/server/lib/agentValidation.js
+++ b/server/lib/agentValidation.js
@@ -80,6 +80,9 @@ export const agentUpdateSchema = partialWithoutDefaults(agentSchema).extend({
// provider prompt.
export const agentGenerateSchema = z.object({
seed: agentSchema.partial().extend({
+ // A blank form asks the generator to invent the name; only persisted
+ // personalities require a non-empty name.
+ name: z.string().max(100).optional(),
personality: partialWithoutDefaults(agentPersonalitySchema).optional(),
}).optional().default({}),
providerId: z.string().min(1).max(128).nullable().optional(),
diff --git a/server/routes/agentPersonalities.test.js b/server/routes/agentPersonalities.test.js
index 2a2066a065..0f7bddfc5e 100644
--- a/server/routes/agentPersonalities.test.js
+++ b/server/routes/agentPersonalities.test.js
@@ -140,6 +140,25 @@ describe('Agent Personalities Routes', () => {
expect(response.status).toBe(200);
expect(generateAgentPersonality).toHaveBeenCalledWith({}, undefined, undefined);
});
+
+ it('generates a name from the blank seed sent by the new-agent form', async () => {
+ generateAgentPersonality.mockResolvedValue({ name: 'New Guide' });
+ const seed = {
+ name: '', description: '',
+ personality: { style: 'casual', tone: '', topics: [], quirks: [], promptPrefix: '' },
+ avatar: { emoji: '🤖', color: '#3b82f6' },
+ };
+
+ const response = await request(makeApp())
+ .post('/api/agents/personalities/generate')
+ .send({ seed, providerId: null, model: null });
+
+ expect(response.status).toBe(200);
+ expect(response.body).toEqual({ name: 'New Guide' });
+ expect(generateAgentPersonality).toHaveBeenCalledWith(
+ { ...seed, enabled: true }, null, null,
+ );
+ });
});
describe('POST /:id/toggle', () => {
diff --git a/server/services/sprites/walk.js b/server/services/sprites/walk.js
index cda0d22822..b850fff62f 100644
--- a/server/services/sprites/walk.js
+++ b/server/services/sprites/walk.js
@@ -1856,6 +1856,8 @@ async function unlockWalkSetImpl(recordId, { acknowledgeNoClips = false } = {})
throw new ServerError('No finalized walk set to unlock', { status: 409, code: 'WALK_SET_NOT_FINAL' });
}
await assertSetReDerivable(recordId, walkSet, { acknowledgeNoClips });
+ // Validate the selection before removing the intact finalized authority.
+ const previous = await loadSelection(recordId);
await dropFinalizedWalkSet(recordId);
// Seed a fresh (empty) selection so EVERY direction re-opens: with the walk
// set gone each direction would still read `approved` from the old selection
@@ -1864,7 +1866,6 @@ async function unlockWalkSetImpl(recordId, { acknowledgeNoClips = false } = {})
// The set's pinned cycle targets survive: unlocking revises the SAME set, and
// dropping them would silently re-derive a target from whatever direction the
// user happened to re-approve first.
- const previous = await loadSelection(recordId);
await atomicWrite(join(spriteDir(recordId), selectionRelPath(recordId)), {
...seedSelection(recordId),
animationTargets: previous?.animationTargets || {},
diff --git a/server/services/sprites/walk.test.js b/server/services/sprites/walk.test.js
index a717e9dbd3..8a1758a2bf 100644
--- a/server/services/sprites/walk.test.js
+++ b/server/services/sprites/walk.test.js
@@ -1240,6 +1240,19 @@ describe('unlockWalkSet', () => {
expect(reapproved.selection.directions.east.status).toBe('approved');
});
+ it('preserves the finalized set and status when the selection is unreadable', async () => {
+ const id = await finalizedCharacter();
+ const walkDir = join(TEST_ROOT, 'sprites', id, 'walk');
+ const setPath = join(walkDir, `${id}-walk-set-v1.json`);
+ const before = await readFile(setPath, 'utf8');
+ await writeFile(join(walkDir, `${id}-walk-selection-v1.json`), '{broken');
+
+ await expect(unlockWalkSet(id)).rejects.toMatchObject({ code: 'UNREADABLE_STORE' });
+
+ expect(await readFile(setPath, 'utf8')).toBe(before);
+ expect((await records.getRecord(id)).status).toBe('walk-complete');
+ });
+
it('refuses to unlock a legacy source-pipeline import', async () => {
const id = await characterWithLockedAnchors(newId(), ['east']);
await mkdir(join(TEST_ROOT, 'sprites', id, 'walk'), { recursive: true });
diff --git a/server/services/timeCapsule.js b/server/services/timeCapsule.js
index 8b4ff346dc..efcd58ff0a 100644
--- a/server/services/timeCapsule.js
+++ b/server/services/timeCapsule.js
@@ -200,7 +200,9 @@ export async function deleteSnapshot(id) {
if (!exists) return false;
const snapshotFile = join(SNAPSHOTS_DIR, `${id}.json`);
- await unlink(snapshotFile).catch(() => {});
+ await unlink(snapshotFile).catch((err) => {
+ if (err.code !== 'ENOENT') throw err;
+ });
index.snapshots = index.snapshots.filter(s => s.id !== id);
await saveIndex(index);
diff --git a/server/services/timeCapsule.test.js b/server/services/timeCapsule.test.js
index ca9f43d423..fb7dbb793c 100644
--- a/server/services/timeCapsule.test.js
+++ b/server/services/timeCapsule.test.js
@@ -3,9 +3,15 @@
*/
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
import { mkdirSync, rmSync, writeFileSync, existsSync, readFileSync } from 'fs';
+import * as fsPromises from 'fs/promises';
import { join } from 'path';
import { cleanupTempDataRoots, lazyTempDataRoot, makePathsProxy } from '../lib/mockPathsDataRoot.js';
+vi.mock('fs/promises', async (importOriginal) => {
+ const actual = await importOriginal();
+ return { ...actual, unlink: vi.fn(actual.unlink) };
+});
+
vi.mock('../lib/fileUtils.js', async (importOriginal) =>
makePathsProxy(await importOriginal(), { dataRoot: () => lazyTempDataRoot('portos-time-capsule-') }));
@@ -176,4 +182,19 @@ describe('getSnapshot / deleteSnapshot', () => {
await expect(listSnapshots()).resolves.toEqual([]);
expect(existsSync(join(snapshotsDir(), `${snapshot.id}.json`))).toBe(false);
});
+
+ it('keeps a failed deletion visible and retryable, while tolerating an already missing file', async () => {
+ const snapshot = await createSnapshot('retry-delete');
+ const error = Object.assign(new Error('permission denied'), { code: 'EACCES' });
+ vi.mocked(fsPromises.unlink).mockRejectedValueOnce(error);
+
+ await expect(deleteSnapshot(snapshot.id)).rejects.toBe(error);
+ expect((await listSnapshots()).map(s => s.id)).toEqual([snapshot.id]);
+ expect(await getSnapshot(snapshot.id)).toMatchObject({ id: snapshot.id });
+
+ // A file removed outside PortOS can still have its stale listing deleted.
+ rmSync(join(snapshotsDir(), `${snapshot.id}.json`));
+ await expect(deleteSnapshot(snapshot.id)).resolves.toBe(true);
+ await expect(listSnapshots()).resolves.toEqual([]);
+ });
});