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: address release review regressions
[._.]/ Adam Eivyfa0bfaafa3ec
diff --git a/client/src/components/meatspace/post/MorseTrainer.jsx b/client/src/components/meatspace/post/MorseTrainer.jsxindex dfa5ebb686..31de374318 100644--- a/client/src/components/meatspace/post/MorseTrainer.jsx+++ b/client/src/components/meatspace/post/MorseTrainer.jsx@@ -284,14 +284,31 @@ function useKeyingDecoder({ unitMs, hz, ensureCtx, claimSession, releaseSession,const gen = ++toneGenRef.current;// Claimed BEFORE the resume await so the context comes up on the `playback`// session — the sidetone is output-only and the iPhone's ring/silent switch- // would otherwise mute the whole send drill. A rejected resume never- // reaches stopTone, so it hands the claim back on its way out.+ // would otherwise mute the whole send drill.claimSession();- const ctx = await ensureCtx().catch((err) => { releaseSession(); throw err; });+ const ctx = await ensureCtx().catch((err) => {+ // claimSession has one slot. A newer key press replaces this claim while+ // the first resume is pending, so an older failure must not release the+ // newer press's playback session.+ if (gen === toneGenRef.current) {+ releaseSession();+ pressingRef.current = false;+ setPressing(false);+ }+ console.error(`❌ Morse sidetone unavailable: ${err.message}`);+ return null;+ });// Unmounting close()s and nulls the per-mount context, so a press parked in// the unlock window resumes with nothing to sound into (same bail as// CopyDrill.playPrompt). Release rather than throwing into createOscillator.- if (!ctx) { releaseSession(); return; }+ if (!ctx) {+ if (gen === toneGenRef.current) {+ releaseSession();+ pressingRef.current = false;+ setPressing(false);+ }+ return;+ }// A fast tap can release (endPress → stopTone), or a newer press can start,// before the first-press-only resume await settles. Bail if the key is no// longer held (`!pressingRef.current`) OR a newer press superseded this one@@ -917,6 +934,7 @@ function CopyDrill({ prefs, updatePrefs, ensureCtx, claimSession, releaseSessionconst [results, setResults] = useState([]);const [feedback, setFeedback] = useState(null);const [playing, setPlaying] = useState(false);+ const [playbackError, setPlaybackError] = useState(null);const [done, setDone] = useState(false);const inputRef = useRef(null);const roundStartRef = useRef(0);@@ -945,18 +963,27 @@ function CopyDrill({ prefs, updatePrefs, ensureCtx, claimSession, releaseSessionasync function playPrompt(isNew) {if (playingRef.current) return;playingRef.current = true;+ setPlaybackError(null);// Claimed BEFORE the resume await so the context comes up on the iOS// `playback` session — this drill is pure synth with no media element, so// on the default `auto` session the ring/silent switch mutes the prompt- // while the UI still says "playing...". A rejected resume never reaches the- // release below, so it hands the claim back on its way out.+ // while the UI still says "playing...".claimSession();- const ctx = await ensureCtx().catch((err) => { releaseSession(); throw err; });+ const ctx = await ensureCtx().catch((err) => {+ console.error(`❌ Morse prompt audio unavailable: ${err.message}`);+ return null;+ });// The per-mount context is close()d and nulled on unmount, so a play that// was still inside the iOS unlock window when the trainer went away has// nothing left to sound into. Bail rather than throwing into playMorse — and// hand the claim back, since no teardown will run for this play.- if (!ctx) { releaseSession(); playingRef.current = false; return; }+ if (!ctx) {+ releaseSession();+ setPlaying(false);+ playingRef.current = false;+ setPlaybackError('Audio playback could not start. Check your browser audio settings and try again.');+ return;+ }const text = isNew ? pickKochPrompt(prefs.kochLevel) : prompt;if (isNew) {setPrompt(text);@@ -964,14 +991,22 @@ function CopyDrill({ prefs, updatePrefs, ensureCtx, claimSession, releaseSessionsetFeedback(null);}setPlaying(true);- // `finally`, not a plain sequence: a scheduling failure that rejects here- // would otherwise strand the session claim AND leave `playingRef` true,- // which silently blocks every later Start Round / replay for the session.- await playMorse(ctx, text, prefs).finally(() => {+ // Handle a synthesis failure locally: the handlers that call this function+ // intentionally fire-and-forget, so rethrowing would create an unhandled+ // rejection and strand the round's synchronous re-entrancy guard.+ const played = await playMorse(ctx, text, prefs).then(+ () => true,+ (err) => {+ console.error(`❌ Morse prompt playback failed: ${err.message}`);+ setPlaybackError('Audio playback could not finish. Try replaying the prompt.');+ return false;+ },+ ).finally(() => {releaseSession();setPlaying(false);playingRef.current = false;});+ if (!played) return;questionStartRef.current = Date.now();setTimeout(() => inputRef.current?.focus(), 50);}@@ -1087,6 +1122,7 @@ function CopyDrill({ prefs, updatePrefs, ensureCtx, claimSession, releaseSession? 'Listen to a 10-question round. No code hints on the results screen — pure recall. Hit 90% to unlock the next letter.': 'Listen to a 10-question round. Hit 90% to unlock the next letter.'}</p>+ {playbackError && <p role="alert" className="text-sm text-port-error">{playbackError}</p>}<buttononClick={startRound}className="px-6 py-3 bg-port-accent hover:bg-port-accent/80 text-white font-medium rounded-lg transition-colors inline-flex items-center gap-2"@@ -1099,6 +1135,7 @@ function CopyDrill({ prefs, updatePrefs, ensureCtx, claimSession, releaseSessionreturn (<div className="bg-port-card border border-port-border rounded-lg p-6 space-y-4">+ {playbackError && <p role="alert" className="text-sm text-port-error">{playbackError}</p>}<div className="flex items-center justify-between text-xs text-gray-500"><span>Question {results.length + 1} / {ROUND_SIZE}</span><buttondiff --git a/client/src/components/meatspace/post/MorseTrainer.test.jsx b/client/src/components/meatspace/post/MorseTrainer.test.jsxindex a1931cb0d9..73cfa9fd38 100644--- a/client/src/components/meatspace/post/MorseTrainer.test.jsx+++ b/client/src/components/meatspace/post/MorseTrainer.test.jsx@@ -498,6 +498,31 @@ describe('MorseTrainer iOS audio session', () => {await waitFor(() => expect(navigator.audioSession.type).toBe('auto'));});+ it('recovers the copy drill after an audio resume rejection', async () => {+ let resumes = 0;+ class FlakyAudioContext extends MockAudioContext {+ constructor() { super(); this.state = 'suspended'; }+ resume() {+ resumes += 1;+ if (resumes === 1) return Promise.reject(new Error('permission denied'));+ this.state = 'running';+ return Promise.resolve();+ }+ }+ window.AudioContext = FlakyAudioContext;+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});+ await renderMorse({ mode: 'copy', onSelectMode: vi.fn(), onExitMode: vi.fn() });++ fireEvent.click(await screen.findByRole('button', { name: /Start Round/i }));+ expect(await screen.findByRole('alert')).toHaveTextContent('Audio playback could not start');+ expect(navigator.audioSession.type).toBe('auto');++ fireEvent.click(screen.getByRole('button', { name: /Start Round/i }));+ await screen.findByPlaceholderText('????');+ expect(resumes).toBe(2);+ errorSpy.mockRestore();+ });+it('claims playback while the send sidetone is keyed and hands it back on release', async () => {await renderMorse({ mode: 'send', onSelectMode: vi.fn(), onExitMode: vi.fn() });await act(async () => { fireEvent.keyDown(window, { code: 'Space' }); });@@ -530,6 +555,32 @@ describe('MorseTrainer iOS audio session', () => {expect(navigator.audioSession.type).toBe('auto');});+ it('keeps a newer sidetone claim when an older resume fails', async () => {+ const resumes = [];+ class DeferredAudioContext extends MockAudioContext {+ constructor() { super(); this.state = 'suspended'; }+ resume() {+ return new Promise((resolve, reject) => resumes.push({ resolve, reject }));+ }+ }+ window.AudioContext = DeferredAudioContext;+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});+ await renderMorse({ mode: 'send', onSelectMode: vi.fn(), onExitMode: vi.fn() });++ fireEvent.keyDown(window, { code: 'Space' });+ fireEvent.keyUp(window, { code: 'Space' });+ fireEvent.keyDown(window, { code: 'Space' });+ expect(navigator.audioSession.type).toBe('playback');++ await act(async () => { resumes[0].reject(new Error('first resume failed')); });+ expect(navigator.audioSession.type).toBe('playback');++ await act(async () => { resumes[1].resolve(); });+ fireEvent.keyUp(window, { code: 'Space' });+ expect(navigator.audioSession.type).toBe('auto');+ errorSpy.mockRestore();+ });+// Unmounting inside the unlock window close()s and nulls the per-mount// context, so the parked playPrompt resumes with nothing to sound into. It// must bail rather than throw into playMorse, and the claim must be gone.diff --git a/client/src/components/videoGen/GalleryVideoPicker.jsx b/client/src/components/videoGen/GalleryVideoPicker.jsxindex 966a5e6a62..625b7ae849 100644--- a/client/src/components/videoGen/GalleryVideoPicker.jsx+++ b/client/src/components/videoGen/GalleryVideoPicker.jsx@@ -10,7 +10,7 @@// REFERENCED by a synced record (e.g. a mood-board item), because// /api/uploads' scratch dir does not federate.-import { useEffect, useMemo, useState } from 'react';+import { useEffect, useMemo, useRef, useState } from 'react';import { Search, X, RefreshCw, Upload } from 'lucide-react';import Modal from '../ui/Modal';import FilePickerButton from '../ui/FilePickerButton';@@ -30,6 +30,14 @@ export default function GalleryVideoPicker({ open, onClose, onSelect, allowUploaconst [loading, setLoading] = useState(false);const [uploading, setUploading] = useState(false);const [query, setQuery] = useState('');+ // Invalidate on every open/close transition and on unmount. A host can+ // change its selected record while an upload is reading or posting; a late+ // completion must leave the saved gallery asset unselected.+ const sessionRef = useRef(0);+ useEffect(() => {+ sessionRef.current += 1;+ return () => { sessionRef.current += 1; };+ }, [open]);useEffect(() => {if (!open) { setQuery(''); return undefined; }@@ -62,14 +70,17 @@ export default function GalleryVideoPicker({ open, onClose, onSelect, allowUploatoast.error(`Video is too large (${formatBytes(file.size)}). Max ${formatBytes(JSON_UPLOAD_MAX_FILE_SIZE)}.`);return;}+ const session = sessionRef.current;setUploading(true);const base64 = await readFileAsBase64(file).catch(() => null);+ if (sessionRef.current !== session) return;if (!base64) { setUploading(false); toast.error(`Failed to read ${file.name}`); return; }if (uploadToGallery) {const entry = await uploadGalleryVideo(base64, file.name, { silent: true }).catch((err) => {- toast.error(err?.message || 'Upload failed');+ if (sessionRef.current === session) toast.error(err?.message || 'Upload failed');return null;});+ if (sessionRef.current !== session) return;setUploading(false);if (!entry?.filename) return;onSelect?.(normalizeVideo(entry));@@ -77,9 +88,10 @@ export default function GalleryVideoPicker({ open, onClose, onSelect, allowUploareturn;}const saved = await uploadFile(base64, file.name, { silent: true }).catch((err) => {- toast.error(err?.message || 'Upload failed');+ if (sessionRef.current === session) toast.error(err?.message || 'Upload failed');return null;});+ if (sessionRef.current !== session) return;setUploading(false);if (!saved?.filename) return;onSelect?.({diff --git a/client/src/components/videoGen/GalleryVideoPicker.test.jsx b/client/src/components/videoGen/GalleryVideoPicker.test.jsxindex b103a2c832..81474c478f 100644--- a/client/src/components/videoGen/GalleryVideoPicker.test.jsx+++ b/client/src/components/videoGen/GalleryVideoPicker.test.jsx@@ -1,9 +1,10 @@import { describe, it, expect, vi, beforeEach } from 'vitest';-import { render, screen, fireEvent, waitFor } from '@testing-library/react';+import { act, render, screen, fireEvent, waitFor } from '@testing-library/react';import GalleryVideoPicker from './GalleryVideoPicker';const listVideoHistory = vi.fn();const uploadGalleryVideo = vi.fn();+const readFileAsBase64 = vi.fn();vi.mock('../../services/apiImageVideo', () => ({listVideoHistory: (...args) => listVideoHistory(...args),uploadGalleryVideo: (...args) => uploadGalleryVideo(...args),@@ -14,7 +15,7 @@ vi.mock('../../services/apiMedia', () => ({}));vi.mock('../../utils/fileUpload', () => ({- readFileAsBase64: vi.fn().mockResolvedValue('ZmFrZQ=='),+ readFileAsBase64: (...args) => readFileAsBase64(...args),JSON_UPLOAD_MAX_FILE_SIZE: 41 * 1024 * 1024,}));@@ -30,6 +31,8 @@ describe('GalleryVideoPicker', () => {listVideoHistory.mockReset();listVideoHistory.mockResolvedValue(HISTORY);uploadGalleryVideo.mockReset();+ readFileAsBase64.mockReset();+ readFileAsBase64.mockResolvedValue('ZmFrZQ==');});it('does not fetch when closed', () => {@@ -72,4 +75,36 @@ describe('GalleryVideoPicker', () => {})));expect(onClose).toHaveBeenCalled();});++ it('drops a gallery upload that lands after the picker was dismissed', async () => {+ let settleUpload;+ uploadGalleryVideo.mockReturnValue(new Promise((resolve) => { settleUpload = resolve; }));+ const onSelect = vi.fn();+ const onClose = vi.fn();+ const { rerender } = render(<GalleryVideoPicker open onClose={onClose} onSelect={onSelect} allowUpload uploadToGallery />);+ const fileInput = document.querySelector('input[type="file"]');+ fireEvent.change(fileInput, { target: { files: [new File(['x'], 'clip.mp4', { type: 'video/mp4' })] } });+ await waitFor(() => expect(uploadGalleryVideo).toHaveBeenCalledTimes(1));++ rerender(<GalleryVideoPicker open={false} onClose={onClose} onSelect={onSelect} allowUpload uploadToGallery />);+ await act(async () => { settleUpload({ id: 'upload-ab12cd34', filename: 'late.mp4', thumbnail: 'late.jpg' }); });++ expect(onSelect).not.toHaveBeenCalled();+ expect(onClose).not.toHaveBeenCalled();+ });++ it('drops a gallery upload that lands after the picker unmounted', async () => {+ let settleUpload;+ uploadGalleryVideo.mockReturnValue(new Promise((resolve) => { settleUpload = resolve; }));+ const onSelect = vi.fn();+ const { unmount } = render(<GalleryVideoPicker open onClose={vi.fn()} onSelect={onSelect} allowUpload uploadToGallery />);+ const fileInput = document.querySelector('input[type="file"]');+ fireEvent.change(fileInput, { target: { files: [new File(['x'], 'clip.mp4', { type: 'video/mp4' })] } });+ await waitFor(() => expect(uploadGalleryVideo).toHaveBeenCalledTimes(1));++ unmount();+ await act(async () => { settleUpload({ id: 'upload-ab12cd34', filename: 'late.mp4', thumbnail: 'late.jpg' }); });++ expect(onSelect).not.toHaveBeenCalled();+ });});diff --git a/data/cos/branch-reconcile-verdicts.json b/data/cos/branch-reconcile-verdicts.jsondeleted file mode 100644index 582ba7e16b..0000000000--- a/data/cos/branch-reconcile-verdicts.json+++ /dev/null@@ -1,42 +0,0 @@-{- "version": 1,- "entries": [- {- "branch": "claim/issue-4170",- "repoPath": "/Users/antic/github.com/atomantic/PortOS",- "verdict": "SUPERSEDED",- "tip": "62dc6747e3d29708f3beca4548aaf8882b3ed39b",- "dirtyPaths": [],- "collisionPaths": [- "client/src/components/ui/CollapsibleText.jsx",- "client/src/components/ui/CollapsibleText.test.jsx"- ],- "replacedBy": [- "660539960d68a28364448e4794c8753dfe489ece",- "4ff7306dfd70034d8175cb32c82604123d84ccd9",- "587c0aeab2bf73760fd1ee7b452c6e9fbef57cc8",- "c5e2bb865e823a2eec6f19399fa050f6c3de39ee"- ],- "replacedByNote": "CollapsibleText.jsx and CollapsibleText.test.jsx on main now remeasure mode changes, count renderable children, and measure overflow live on focus.",- "was": "Refresh CollapsibleText behavior for content-mode switches, empty child lists, and focus within clipped children.",- "decidedAt": "2026-08-15T06:05:05Z"- },- {- "branch": "cos/sys-mstr08m7/agent-184bb093",- "repoPath": "/Users/adameivy/github.com/atomantic/PortOS",- "verdict": "SUPERSEDED",- "tip": "708422216e865e10278b2cb414a0382ec8f6e247",- "dirtyPaths": [],- "collisionPaths": [- "server/lib/primaryCheckoutGuard.js",- "server/lib/primaryCheckoutGuard.test.js"- ],- "replacedBy": [- "cf7f356a1c693282da5100b9bee40ab83ffd5d61"- ],- "replacedByNote": "server/lib/primaryCheckoutGuard.js now treats unrelated branch switches with strandedCount === 0 as unattributed instead of failing the run, and server/lib/primaryCheckoutGuard.test.js covers that behavior.",- "was": "Stop failing a worktree agent when another branch switch someone else made in the primary checkout left no attributable commits.",- "decidedAt": "2026-08-15T06:37:34Z"- }- ]-}diff --git a/scripts/migrations/270-cos-task-prompt-split.js b/scripts/migrations/270-cos-task-prompt-split.jsindex 95a9d8d612..55b86a86d6 100644--- a/scripts/migrations/270-cos-task-prompt-split.js+++ b/scripts/migrations/270-cos-task-prompt-split.js@@ -178,7 +178,17 @@ export function splitPromptMetadata(markdown, { stamp }) {*/async function queuePaths(rootDir) {const raw = await readFile(join(rootDir, 'data', 'cos', 'state.json'), 'utf-8').catch(() => null);- const config = raw ? JSON.parse(raw)?.config ?? {} : {};+ let config = {};+ if (raw) {+ try {+ config = JSON.parse(raw)?.config ?? {};+ } catch {+ // State recovery is intentionally tolerant elsewhere. A malformed+ // optional config file must not prevent this migration from splitting+ // the default queues and letting the normal state loader repair it.+ console.warn('⚠️ migration 270: invalid CoS state; using default task queue paths');+ }+ }return QUEUE_FILES.map(({ configKey, file }) => (typeof config[configKey] === 'string' && config[configKey] ? config[configKey] : file));diff --git a/scripts/migrations/270-cos-task-prompt-split.test.js b/scripts/migrations/270-cos-task-prompt-split.test.jsindex d6b7700269..85708ad7d5 100644--- a/scripts/migrations/270-cos-task-prompt-split.test.js+++ b/scripts/migrations/270-cos-task-prompt-split.test.js@@ -1,4 +1,4 @@-import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { mkdir, mkdtemp, readFile, rm, writeFile } from 'fs/promises';import { tmpdir } from 'os';import { join } from 'path';@@ -215,4 +215,16 @@ describe('migration 270 up()', () => {await expect(migration.up({ rootDir, now: STAMP })).resolves.toMatchObject({ ok: true, split: 1 });expect(parseTasksMarkdown(await readFile(moved, 'utf-8'))[0].metadata.prompt).toBe(AGENT_BODY);});++ it('falls back to the default queues when CoS state is malformed', async () => {+ await mkdir(join(rootDir, 'data', 'cos'), { recursive: true });+ await writeFile(join(rootDir, 'data', 'cos', 'state.json'), '{not valid json');+ await writeFile(cosTasks(), queue(task('sys-1', { context: AGENT_BODY })));+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});++ await expect(migration.up({ rootDir, now: STAMP })).resolves.toMatchObject({ ok: true, split: 1 });++ expect(parseTasksMarkdown(await readFile(cosTasks(), 'utf-8'))[0].metadata.prompt).toBe(AGENT_BODY);+ expect(warn).toHaveBeenCalledWith(expect.stringContaining('invalid CoS state'));+ });});diff --git a/server/routes/openclaw.js b/server/routes/openclaw.jsindex 67e1c33306..522f7b351a 100644--- a/server/routes/openclaw.js+++ b/server/routes/openclaw.js@@ -11,6 +11,7 @@ import {streamSessionMessage} from '../integrations/openclaw/api.js';import { onClientDisconnect, openSseStream } from '../lib/sseDownload.js';+import { awaitWritableDrain } from '../lib/streamBackpressure.js';const router = express.Router();@@ -203,7 +204,7 @@ router.post('/sessions/:id/messages/stream', asyncHandler(async (req, res) => {if (done || clientDisconnected || res.writableEnded || res.destroyed) break;if (value) {const canContinue = res.write(decoder.decode(value, { stream: true }));- if (!canContinue) await new Promise(resolve => res.once('drain', resolve));+ if (!canContinue) await awaitWritableDrain(res);}}const tail = decoder.decode();diff --git a/server/routes/openclaw.test.js b/server/routes/openclaw.test.jsindex 2d7dd5f1c1..db35508b52 100644--- a/server/routes/openclaw.test.js+++ b/server/routes/openclaw.test.js@@ -518,6 +518,87 @@ describe('OpenClaw Routes', () => {}});+ it('leaves a backpressured SSE wait when its client disconnects', async () => {+ openclawApi.isConfigured.mockResolvedValue(CONFIGURED_STATUS);++ let finishRead;+ const pendingRead = new Promise((resolve) => { finishRead = resolve; });+ let markReaderCancelled;+ const readerCancelled = new Promise((resolve) => { markReaderCancelled = resolve; });+ let reads = 0;+ const mockReader = {+ read: vi.fn(() => {+ if (reads++ === 0) return Promise.resolve({ done: false, value: Buffer.from('data: first\\n\\n') });+ return pendingRead;+ }),+ cancel: vi.fn(async () => {+ markReaderCancelled();+ finishRead({ done: true, value: undefined });+ }),+ };+ openclawApi.streamSessionMessage.mockResolvedValue({+ response: { ok: true, body: { getReader: vi.fn(() => mockReader) } },+ });++ let markBackpressured;+ const backpressured = new Promise((resolve) => { markBackpressured = resolve; });+ let markRouteEnded;+ const routeEnded = new Promise((resolve) => { markRouteEnded = resolve; });+ const backpressureApp = express();+ backpressureApp.use(express.json({ limit: '55mb' }));+ backpressureApp.use((_req, res, next) => {+ const write = res.write.bind(res);+ const end = res.end.bind(res);+ let firstWrite = true;+ res.write = (...args) => {+ if (firstWrite) {+ firstWrite = false;+ markBackpressured();+ return false;+ }+ return write(...args);+ };+ res.end = (...args) => {+ markRouteEnded();+ return end(...args);+ };+ next();+ });+ backpressureApp.use('/api/openclaw', openclawRoutes);++ const server = await startLoopbackServer(backpressureApp);+ let client;+ try {+ const body = JSON.stringify({ message: 'Disconnect while backpressured' });+ client = httpRequest({+ hostname: '127.0.0.1',+ port: server.address().port,+ method: 'POST',+ path: '/api/openclaw/sessions/main/messages/stream',+ headers: {+ 'content-type': 'application/json',+ 'content-length': Buffer.byteLength(body),+ },+ });+ client.on('error', () => {});+ client.end(body);++ await backpressured;+ client.destroy();+ await readerCancelled;+ await Promise.race([+ routeEnded,+ new Promise((_, reject) => setTimeout(() => reject(new Error('route remained backpressured after close')), 1000)),+ ]);++ expect(mockReader.cancel).toHaveBeenCalledTimes(1);+ } finally {+ client?.destroy();+ finishRead({ done: true, value: undefined });+ await closeLoopbackServer(server);+ }+ });+it('should write an error SSE event when upstream body is null', async () => {openclawApi.isConfigured.mockResolvedValue({ configured: true, enabled: true });openclawApi.streamSessionMessage.mockResolvedValue({ response: { ok: true, body: null } });diff --git a/server/routes/videoGen.js b/server/routes/videoGen.jsindex 9464d38f1f..fdf26eda8d 100644--- a/server/routes/videoGen.js+++ b/server/routes/videoGen.js@@ -1281,17 +1281,21 @@ router.post('/history/:id/visibility', asyncHandler(async (req, res) => {res.json(await setHistoryItemHidden(req.params.id, !!req.body?.hidden));}));+// Render jobs use UUID history ids, while shared-gallery uploads use an+// `upload-<uuid8>` id. These mutating operations only resolve a stored history+// record and subsequently derive the path from its guarded filename, so both+// known id forms are valid here.+const historyIdSchema = z.string().regex(+ /^(?:[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}|upload-[a-f0-9]{8})$/i,+ 'invalid history id',+);+router.post('/last-frame/:id', asyncHandler(async (req, res) => {- res.json(await extractLastFrame(req.params.id));+ const parsed = historyIdSchema.safeParse(req.params.id);+ if (!parsed.success) failValidation(parsed);+ res.json(await extractLastFrame(parsed.data));}));-// History ids are produced by crypto.randomUUID(), so validate them as-// UUIDs rather than the looser /^[a-f0-9-]{36}$/ pattern (which happily-// accepts e.g. 36 hyphens). `.guid()` is Zod 4's name for the 8-4-4-4-12-// hex-group check Zod 3's `.uuid()` performed (version-agnostic); matches-// the .guid() usage in the other route schemas.-const historyIdSchema = z.string().guid('invalid history id');-router.post('/upscale/:id', asyncHandler(async (req, res) => {const parsed = historyIdSchema.safeParse(req.params.id);if (!parsed.success) failValidation(parsed);diff --git a/server/routes/videoGen.test.js b/server/routes/videoGen.test.jsindex 5721120583..268522e01f 100644--- a/server/routes/videoGen.test.js+++ b/server/routes/videoGen.test.js@@ -2155,6 +2155,25 @@ describe('videoGen routes', () => {});});+ describe('POST /last-frame/:id', () => {+ it('forwards a shared-gallery upload id to extractLastFrame', async () => {+ const uploadId = 'upload-ab12cd34';+ videoGenService.extractLastFrame.mockResolvedValue({ filename: `lastframe-${uploadId}.png` });++ const r = await request(app).post(`/api/video-gen/last-frame/${uploadId}`).send({});++ expect(r.status).toBe(200);+ expect(videoGenService.extractLastFrame).toHaveBeenCalledWith(uploadId);+ });++ it('rejects malformed ids before extracting a frame', async () => {+ const r = await request(app).post('/api/video-gen/last-frame/not-a-history-id').send({});++ expect(r.status).toBe(400);+ expect(videoGenService.extractLastFrame).not.toHaveBeenCalled();+ });+ });+describe('POST /stitch', () => {const validId = (n) => `aaaaaaaa-aaaa-4aaa-aaaa-aaaaaaaaaaa${n}`;@@ -2181,13 +2200,21 @@ describe('videoGen routes', () => {expect(r.body.video.id).toBe('s1');expect(videoGenService.stitchVideos).toHaveBeenCalledWith([validId(1), validId(2)]);});++ it('accepts a shared-gallery upload history id', async () => {+ videoGenService.stitchVideos.mockResolvedValue({ id: 's1', filename: 's1.mp4' });+ const uploadId = 'upload-ab12cd34';+ const r = await request(app).post('/api/video-gen/stitch').send({ videoIds: [uploadId, validId(2)] });+ expect(r.status).toBe(200);+ expect(videoGenService.stitchVideos).toHaveBeenCalledWith([uploadId, validId(2)]);+ });});describe('POST /upscale/:id', () => {const validHistoryId = 'aaaaaaaa-aaaa-4aaa-aaaa-aaaaaaaaaaa1';const otherValidId = 'bbbbbbbb-bbbb-4bbb-bbbb-bbbbbbbbbbb2';- it('rejects history ids that do not match the UUID shape', async () => {+ it('rejects history ids outside known render and upload shapes', async () => {const r = await request(app).post('/api/video-gen/upscale/not-a-uuid').send({});expect(r.status).toBe(400);expect(videoGenService.upscaleHistoryItem).not.toHaveBeenCalled();@@ -2203,6 +2230,14 @@ describe('videoGen routes', () => {expect(videoGenService.upscaleHistoryItem).toHaveBeenCalledWith(validHistoryId);});+ it('forwards a shared-gallery upload id to upscaleHistoryItem', async () => {+ const uploadId = 'upload-ab12cd34';+ videoGenService.upscaleHistoryItem.mockResolvedValue({ id: otherValidId, filename: `${otherValidId}.mp4`, upscaledFrom: uploadId });+ const r = await request(app).post(`/api/video-gen/upscale/${uploadId}`).send({});+ expect(r.status).toBe(200);+ expect(videoGenService.upscaleHistoryItem).toHaveBeenCalledWith(uploadId);+ });+it('returns the ServerError status when the service rejects', async () => {videoGenService.upscaleHistoryItem.mockRejectedValue(Object.assign(new Error('Video not found'), { status: 404, code: 'NOT_FOUND' }),diff --git a/server/services/agentCliSpawning.js b/server/services/agentCliSpawning.jsindex 37b1045e44..49847eb296 100644--- a/server/services/agentCliSpawning.js+++ b/server/services/agentCliSpawning.js@@ -40,6 +40,8 @@ import { prClaimWasVerified, resolvePrCompletion, resolvePrCreation } from '../limport { canTypeSlashCommands, agentOwnsPrWorkflow } from '../lib/slashdoInvocation.js';import { doneSentinelPath } from '../lib/agentSentinel.js';import { isHostShuttingDown, shouldAbandonForHostShutdown, HOST_SHUTDOWN_REASON } from '../lib/hostShutdown.js';+import { ensureOllamaAgentContext } from './ollamaAgentContext.js';+import { isOllamaBackedProvider } from './providers.js';const AGENTS_DIR = PATHS.cosAgents;@@ -341,6 +343,18 @@ export async function spawnDirectly({// Ensure workspacePath is validconst cwd = workspacePath && typeof workspacePath === 'string' ? workspacePath : ROOT_DIR;+ // Direct CLI agents bypass runner.js, so their Ollama-backed harnesses need+ // the same daemon context preparation as runner and TUI launches. This is+ // deliberately before spawn: a per-request window cannot reach a CLI that+ // talks to Ollama on its own.+ const ollamaContext = isOllamaBackedProvider(provider) ? await ensureOllamaAgentContext(provider) : null;+ if (ollamaContext?.warning) {+ emitLog('warn', `Agent ${agentId} Ollama context preparation: ${ollamaContext.warning}`, {+ agentId,+ taskId: task.id,+ });+ }+// Two independent async env lookups, resolved together: Claude's// ~/.claude/settings.json Bedrock config (CLAUDE_CODE_USE_BEDROCK, AWS_PROFILE,// etc., present even if PM2 lacks them) and the repo-owner-pinned GH_TOKEN@@ -431,6 +445,8 @@ export async function spawnDirectly({// handlers `await outputBatcher.flush()` so the final lines persist before// the agent is finalized. (output.txt is written separately below.)const outputBatcher = createAgentOutputBatcher(agentId);+ if (ollamaContext?.warning) outputBatcher.push(ollamaContext.warning);+ if (ollamaContext?.applied) outputBatcher.push(`🪟 Reloaded Ollama at a ${ollamaContext.contextLength}-token context window`);// Expose a drain hook on the activeAgents entry so the user-terminate/kill// paths (agentManagement.js) can flush pending batched output before theydiff --git a/server/services/agentCliSpawning.test.js b/server/services/agentCliSpawning.test.jsindex 042b252b5e..6f1ddc048c 100644--- a/server/services/agentCliSpawning.test.js+++ b/server/services/agentCliSpawning.test.js@@ -97,9 +97,17 @@ vi.mock('../lib/childProcess.js', () => ({vi.mock('./agentWorktreeCleanup.js', () => ({releaseRetryHold: vi.fn().mockResolvedValue({}),}));+vi.mock('./ollamaAgentContext.js', () => ({+ ensureOllamaAgentContext: vi.fn(async () => ({ skipped: true })),+}));+vi.mock('./providers.js', () => ({+ isOllamaBackedProvider: vi.fn(() => false),+}));import { buildCliSpawnConfig, createStreamJsonParser, spawnDirectly } from './agentCliSpawning.js';import { releaseRetryHold } from './agentWorktreeCleanup.js';+import { ensureOllamaAgentContext } from './ollamaAgentContext.js';+import { isOllamaBackedProvider } from './providers.js';// Real module — the flag is a plain process-local boolean, so driving it// directly exercises the same code path production does.import { markHostShuttingDown, resetHostShutdownFlagForTests } from '../lib/hostShutdown.js';@@ -531,6 +539,8 @@ describe('stream error containment', () => {(await import('./agentFinalization.js')).finalizeAgent.mockResolvedValue(undefined);minimalArgs.cleanupWorktreeFn.mockResolvedValue(undefined);vi.mocked(existsSync).mockReturnValue(false);+ vi.mocked(isOllamaBackedProvider).mockReturnValue(false);+ vi.mocked(ensureOllamaAgentContext).mockResolvedValue({ skipped: true });// Reset the resolve+wrap helper to its POSIX passthrough before each test// (afterEach's restoreAllMocks can clear the factory implementation).vi.mocked(prepareCliSpawn).mockImplementation((command, args) => ({ command, args }));@@ -583,6 +593,36 @@ describe('stream error containment', () => {expect(logged).toBe(true);});+ it('prepares the configured Ollama context before a direct CLI agent spawns', async () => {+ vi.mocked(spawn).mockClear();+ vi.mocked(ensureOllamaAgentContext).mockClear();+ vi.mocked(isOllamaBackedProvider).mockReturnValue(true);+ vi.mocked(ensureOllamaAgentContext).mockResolvedValue({+ skipped: false,+ applied: true,+ contextLength: 131072,+ warning: '⚠️ Example context warning',+ });++ const spawnPromise = spawnDirectly({+ ...minimalArgs,+ provider: { ...minimalArgs.provider, id: 'claude-ollama', ollamaBacked: true },+ });+ await new Promise((r) => setTimeout(r, 10));++ expect(ensureOllamaAgentContext).toHaveBeenCalledWith(expect.objectContaining({ id: 'claude-ollama' }));+ expect(ensureOllamaAgentContext.mock.invocationCallOrder[0]).toBeLessThan(spawn.mock.invocationCallOrder[0]);++ fakeProcess.emit('close', 0);+ await spawnPromise;+ await new Promise((r) => setTimeout(r, 20));++ expect(agentStateMocks.appendAgentOutputLines).toHaveBeenCalledWith('agent-test', [+ '⚠️ Example context warning',+ '🪟 Reloaded Ollama at a 131072-token context window',+ ]);+ });+it('drains stderr output on close and a failed batch flush is logged, not leaked as an unhandled rejection', async () => {agentStateMocks.appendAgentOutputLines.mockRejectedValueOnce(new Error('stderr db write failed'));diff --git a/server/services/mediaPromptFromMedia.js b/server/services/mediaPromptFromMedia.jsindex 17706e0ff4..f74751f66f 100644--- a/server/services/mediaPromptFromMedia.js+++ b/server/services/mediaPromptFromMedia.js@@ -35,7 +35,10 @@ const MAX_PROMPT_LEN = 8000;const MAX_REASON_LEN = 1200;const MAX_FRAMES = 5;const VISION_TIMEOUT_MS = 180000;-const VIDEO_ID_RE = /^[a-f0-9-]{36}$/i;+// Render jobs use UUID history ids, while gallery uploads deliberately use an+// `upload-<uuid8>` stem for their id, video filename, and thumbnail. Both are+// gallery history records, so prompt-from-media must resolve either form.+const VIDEO_ID_RE = /^(?:[a-f0-9-]{36}|upload-[a-f0-9]{8})$/i;const IMAGE_EXT_RE = /\.(png|jpe?g|gif|webp)$/i;const VIDEO_EXT_RE = /\.(mp4|webm|mov|m4v|mkv)$/i;diff --git a/server/services/mediaPromptFromMedia.test.js b/server/services/mediaPromptFromMedia.test.jsindex c1a1b75809..4844c0a067 100644--- a/server/services/mediaPromptFromMedia.test.js+++ b/server/services/mediaPromptFromMedia.test.js@@ -193,6 +193,28 @@ describe('promptFromMedia', () => {expect(result.frameCount).toBe(2);});+ it('samples an uploaded gallery video by its upload history id', async () => {+ providers.getProviderById.mockResolvedValue(CLI_PROVIDER);+ visionCli.describeImagesFromPaths.mockResolvedValue({ text: JSON_BOTH });+ history.loadHistory.mockResolvedValue([+ { id: 'upload-ab12cd34', filename: 'upload-ab12cd34.mp4' },+ ]);++ const result = await promptFromMedia({+ sourceKind: 'video',+ videoId: 'upload-ab12cd34',+ targets: ['video'],+ providerId: 'codex',+ });++ expect(ffmpeg.extractEvaluationFrames).toHaveBeenCalledWith(+ '/mock/videos/upload-ab12cd34.mp4',+ 'pfm-upload-ab12cd34',+ expect.any(Number),+ );+ expect(result.mediaKind).toBe('video');+ });+it('resolves a gallery video by FILENAME when no videoId is given (mood-board item — #4188)', async () => {providers.getProviderById.mockResolvedValue(CLI_PROVIDER);visionCli.describeImagesFromPaths.mockResolvedValue({ text: JSON_BOTH });diff --git a/server/services/sharing/peerSyncAssets.js b/server/services/sharing/peerSyncAssets.jsindex 39eb172c6e..c3bb79e2e3 100644--- a/server/services/sharing/peerSyncAssets.js+++ b/server/services/sharing/peerSyncAssets.js@@ -449,6 +449,27 @@ async function videoThumbnailNameForVideo(filename) {return null;}+// Regenerate a video poster under the history row's declared name. The helper+// also runs for a hash-matched video: metadata and bytes can arrive in either+// order, and a first pull may have made only the filename-stem fallback before+// a later videoHistory sync declared an independent poster name.+async function reconcileVideoThumbnail(filename, videoPath, peerId) {+ const rowThumbnail = await videoThumbnailNameForVideo(filename).catch(() => null);+ const jobId = (rowThumbnail || filename).replace(/\.[a-z0-9]+$/i, '');+ const expectedFilename = `${jobId}.jpg`;+ if (existsSync(join(PATHS.videoThumbnails, expectedFilename))) return null;++ const thumbFilename = await generateThumbnail(videoPath, jobId).catch(() => null);+ if (thumbFilename) {+ peerSyncEvents.emit('asset-arrived', {+ filename: thumbFilename,+ kind: 'video-thumbnail',+ peerId,+ });+ }+ return thumbFilename;+}+/*** Build a Music Video project's asset manifest (#1772). Unlike the Creative* Director store, a music video project has NO auto-linked media collection, so@@ -919,6 +940,9 @@ async function doPullOneAsset(peer, base, entry, urlPrefix, localDir, safeName)// Bytes already up-to-date. Images still reconcile their sidecar, since// that may be the only reason this entry was flagged.if (entry.kind === 'image') await pullSidecarForImage(peer, base, safeName).catch(() => {});+ // A video can have arrived before its video-history metadata. Recheck+ // the declared poster even though the mp4 itself does not need a pull.+ if (entry.kind === 'video') await reconcileVideoThumbnail(safeName, localFullPath, peer.instanceId);return;}}@@ -946,32 +970,9 @@ async function doPullOneAsset(peer, base, entry, urlPrefix, localDir, safeName)await pullSidecarForImage(peer, base, safeName).catch(() => {});}// After a video pull, regenerate the thumbnail LOCALLY rather than pulling it- // as a sibling asset. Cheaper end-to-end: no new asset kind / URL-prefix /- // manifest-diff plumbing. The NAME comes from the synced video-history row's- // `thumbnail` field (#4162) — NOT the mp4 stem, which is only coincidentally- // right for videoGen clips and flatly wrong for a stitched timeline final (see- // `videoThumbnailNameForVideo`). The stem stays the fallback for the window- // where the bytes beat the `videoHistory` metadata category across.- //- // The regenerated thumbnail then gets its OWN `asset-arrived` emit: the video- // emit above names the `.mp4`, and `MediaImage` matches on filename alone, so- // without this a poster `<img>` that already 404'd sits on the "Syncing"- // placeholder until a remount even though the bytes are on disk.- //- // Best-effort throughout: if ffmpeg is missing the row still syncs (the item- // stops being filtered as "missing"); the tile just falls back to no preview.- // Mirrors generateThumbnail's null-on-failure contract.+ // as a sibling asset. Its own `asset-arrived` event lets a poster that already+ // 404'd leave MediaImage's "Syncing" placeholder without a remount.if (entry.kind === 'video') {- const rowThumbnail = await videoThumbnailNameForVideo(safeName).catch(() => null);- const jobId = (rowThumbnail || safeName).replace(/\.[a-z0-9]+$/i, '');- const videoPath = join(localDir, safeName);- const thumbFilename = await generateThumbnail(videoPath, jobId).catch(() => null);- if (thumbFilename) {- peerSyncEvents.emit('asset-arrived', {- filename: thumbFilename,- kind: 'video-thumbnail',- peerId: peer.instanceId,- });- }+ await reconcileVideoThumbnail(safeName, fullPath, peer.instanceId);}}diff --git a/server/services/sharing/peerSyncAssets.videoThumbnail.test.js b/server/services/sharing/peerSyncAssets.videoThumbnail.test.jsindex f638c0639a..92670264a4 100644--- a/server/services/sharing/peerSyncAssets.videoThumbnail.test.js+++ b/server/services/sharing/peerSyncAssets.videoThumbnail.test.js@@ -140,6 +140,31 @@ describe('#4162 — pulled-video thumbnail naming + arrival event', () => {expect(arrivals.map((a) => a.filename)).toContain('ffffffff-0000-1111-2222-333333333333.jpg');});+ it('reconciles an independent poster name after video-history metadata arrives', async () => {+ const filename = 'timeline-deadbeef-1700000000000.mp4';+ const bytes = Buffer.from('timeline-bytes');+ await pullVideo(filename, bytes);+ expect(vi.mocked(generateThumbnail).mock.calls[0][1]).toBe('timeline-deadbeef-1700000000000');++ writeVideoHistory([{+ id: '22222222-3333-4444-5555-666666666666',+ filename,+ thumbnail: '22222222-3333-4444-5555-666666666666.jpg',+ }]);+ vi.mocked(generateThumbnail).mockClear();++ const arrivals = await pullVideo(filename, bytes);++ expect(vi.mocked(generateThumbnail)).toHaveBeenCalledWith(+ join(tempRoot, 'videos', filename),+ '22222222-3333-4444-5555-666666666666',+ );+ expect(arrivals).toEqual([expect.objectContaining({+ filename: '22222222-3333-4444-5555-666666666666.jpg',+ kind: 'video-thumbnail',+ })]);+ });+it('ignores a traversal-shaped `thumbnail` from a peer row and falls back to the stem', async () => {writeVideoHistory([{id: 'evil',diff --git a/server/services/videoGen/local.js b/server/services/videoGen/local.jsindex ef4fdaa2ad..dfe9749dab 100644--- a/server/services/videoGen/local.js+++ b/server/services/videoGen/local.js@@ -102,6 +102,10 @@ const AV_LORA_HELPER_SCRIPT = join(PATHS.root, 'scripts', 'generate_av_lora.py')const execFileAsync = promisify(execFile);const MODULE_NOT_FOUND_RE = /ModuleNotFoundError: No module named ['"]([^'"]+)['"]/;+// Shared-gallery uploads use the upload filename stem as their history id.+// Rendered clips retain their UUID ids, so service callers may act on either+// form after route validation.+const UPLOADED_HISTORY_ID_RE = /^upload-[a-f0-9]{8}$/i;// Panel-side SIGKILL watchdog (defense-in-depth at the Node layer).//@@ -2330,6 +2334,12 @@ async function setHistoryItemsHidden(ids, hidden) {// Extract the last frame of a video as a PNG into data/images/ — used to// chain a clip into Imagine for "continue from last frame" remixing.export async function extractLastFrame(historyId) {+ // Keep this service safe for callers outside the route layer too. Shared+ // gallery uploads deliberately use `upload-<uuid8>` ids, while generated+ // clips retain UUID ids.+ if (typeof historyId !== 'string' || (!UUID_RE.test(historyId) && !UPLOADED_HISTORY_ID_RE.test(historyId))) {+ throw new ServerError('Invalid history id', { status: 400, code: 'VALIDATION_ERROR' });+ }const history = await loadHistory();const item = history.find((h) => h.id === historyId);if (!item) throw new ServerError('Video not found', { status: 404, code: 'NOT_FOUND' });@@ -2344,9 +2354,10 @@ export async function extractLastFrame(historyId) {await ensureDir(PATHS.images);// Same path-traversal concern as `item.filename` above — `item.id` could// contain path separators or `..` if history.json was tampered with.- // generateVideo writes ids via randomUUID() (matches /^[a-f0-9-]{36}$/),- // so reject anything else outright.- if (!/^[a-f0-9-]{36}$/i.test(item.id)) {+ // Generated clips use UUID ids and uploads use `upload-<uuid8>`; both forms+ // are filename-safe. Do not trust a tampered stored record simply because+ // the caller's id passed validation above.+ if (typeof item.id !== 'string' || (!UUID_RE.test(item.id) && !UPLOADED_HISTORY_ID_RE.test(item.id))) {throw new ServerError('Invalid history id', { status: 400, code: 'VALIDATION_ERROR' });}const frameFilename = `lastframe-${item.id}.png`;@@ -2664,9 +2675,10 @@ export async function upscaleHistoryItem(historyId) {// Validate the input arg first — failing here surfaces a clean 400 even if// the history file happens to contain a record with a malformed id, and// it short-circuits the loadHistory I/O for obviously-bogus requests.- // Use the shared strict UUID regex (the prior /^[a-f0-9-]{36}$/i pattern- // accepted non-UUID 36-char strings like all-hyphens).- if (typeof historyId !== 'string' || !UUID_RE.test(historyId)) {+ // Rendered clips use UUIDs; shared-gallery uploads use their `upload-<uuid8>`+ // filename stem as the id. Keep the strict UUID check for render ids while+ // allowing the upload producer's documented id shape.+ if (typeof historyId !== 'string' || (!UUID_RE.test(historyId) && !UPLOADED_HISTORY_ID_RE.test(historyId))) {throw new ServerError('Invalid history id', { status: 400, code: 'VALIDATION_ERROR' });}const history = await loadHistory();diff --git a/server/services/videoGen/local.test.js b/server/services/videoGen/local.test.jsindex cbf85bdbd0..114a407c1f 100644--- a/server/services/videoGen/local.test.js+++ b/server/services/videoGen/local.test.js@@ -307,12 +307,13 @@ vi.mock('../../lib/detachedSpawn.js', () => ({// Import AFTER all vi.mock calls so the hoisted mocks are in place.let generateChainedVideo;let generateVideo;+let extractLastFrame;let videoGenEvents;beforeEach(async () => {vi.resetModules();// Re-import fresh copies so mock reset above applies cleanly- ({ generateChainedVideo, generateVideo } = await import('./local.js'));+ ({ generateChainedVideo, generateVideo, extractLastFrame } = await import('./local.js'));({ videoGenEvents } = await import('./events.js'));});@@ -321,6 +322,22 @@ afterEach(() => {vi.clearAllMocks();});+describe('extractLastFrame — shared-gallery uploads', () => {+ it('accepts an uploaded gallery history id', async () => {+ const { readJSONFile } = await import('../../lib/fileUtils.js');+ vi.mocked(readJSONFile).mockResolvedValueOnce([{+ id: 'upload-ab12cd34',+ filename: 'upload-ab12cd34.mp4',+ prompt: 'example',+ }]);++ await expect(extractLastFrame('upload-ab12cd34')).resolves.toMatchObject({+ filename: 'lastframe-upload-ab12cd34.png',+ path: '/data/images/lastframe-upload-ab12cd34.png',+ });+ });+});+// ─── helpers ─────────────────────────────────────────────────────────────────/**