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
refactor([apicore-request-arraybuffer-response-type]): collapse TTS audition helpers onto apiCore.request()
[._.]/ Adam Eivyb1b230547593
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 17783337b7..9fe40ab3fa 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -2,6 +2,8 @@## Changed+- **[apicore-request-arraybuffer-response-type] `apiCore.request()` grows an `arraybuffer` `responseType` escape hatch; two TTS audition helpers stop bypassing the shared client.** `client/src/services/apiCore.js#request` now accepts `{ responseType: 'arraybuffer' }` — when set, the helper returns `response.arrayBuffer()` instead of parsing JSON, while still funneling the error path (server-shaped 4xx/5xx, network-unreachable toast, `err.code` / `err.status` / `err.context` forwarding) through the same code. `apiVoice.js#testTts` and `apiPipeline.js#previewPipelineTtsVoice` dropped their raw `fetch` paths and now call `request()` with `responseType: 'arraybuffer'` + `silent: true` (all three callers — `VoiceTab.handleTest`, `VoiceTab.handlePreviewVoice`, `VoicePicker.handleAudition` — already own their own catch-block toasts, so silent avoids double-toasting per the CLAUDE.md convention). Drops ~25 LOC of duplicated `if (!res.ok) parse + throw` shaping. Also pruned a stale PLAN.md entry ([extract-useswipenav-hook-lib-clipboard-js]) — both halves of that item already shipped (clipboard helpers in `client/src/lib/clipboard.js`, swipe in `client/src/hooks/useSwipeNav.js`; `MediaLightbox.jsx:122` has been calling `useSwipeNav` since PR #261). 163/163 client tests pass; lint clean.+- **[datasync-bundle] `dataSync.js` write-pattern + checksum-cache cleanup (2 items).** (1) [datasync-migrate-categories-to-atomicwrite] Replace seven inlined `ensureDir + writeFile(JSON.stringify(...))` triples across the goals/character/digitalTwin/meatspace categories with single `atomicWrite(path, data)` calls — temp+rename atomicity protects readers from seeing a partial write, which matters for the larger pipeline/universe JSON files that other services write concurrently. Pre-loop `ensureDir` calls dropped because each `atomicWrite` ensures its own dirname. (2) [datasync-checksum-only-fast-path] Add a per-category mtime-keyed cache in front of `getChecksum()`. The orchestrator hits this every cycle and previously materialized the full snapshot just to discard `data`; now a `stat`-only path returns the cached checksum when no underlying file changed since the last computation, falling through to `getSnapshot()` on a cache miss. Same checksum value as before — pure optimization, no protocol break. Three new tests cover cache consistency across consecutive calls, invalidation after `applyRemote`, and invalidation on out-of-band file mutations (16/16 dataSync tests pass; 5973/5973 full server suite).- **[med-ai-dispatch-server-services-aidetect-js-242] `aiDetect.js` migrated to `runPromptThroughProvider` — TUI providers now work on Settings → Detect App.** `server/services/aiDetect.js` had a legacy `if (provider.type === 'cli') … else if ('api') … else 'Unknown provider type'` dispatch that rejected TUI providers outright and duplicated spawn/fetch logic the central handler already covers. The two inline functions (`executeCliDetection`, `executeApiDetection`) and the local `spawn`/`fetch` machinery are gone; detection now flows through `runPromptThroughProvider` from `server/lib/promptRunner.js` with `source: 'ai-app-detect'`, `cwd: dirPath` (so a spawned CLI/TUI runs against the analyzed repo, not PortOS's own cwd), and a 60s default timeout. `parseAiResponse` also moved to the shared `extractJson` helper from `server/lib/jsonExtract.js`, which strips CLI banner text and repairs trailing-comma JSON — relevant for TUI providers that emit banner output around the JSON payload. New `server/services/aiDetect.test.js` locks in the dispatch behavior (regression test ensures TUI no longer fails with "Unknown provider type") plus directory + provider-disabled error paths and the banner-stripping JSON case.diff --git a/PLAN.md b/PLAN.mdindex 084341c503..80fed4ac74 100644--- a/PLAN.md+++ b/PLAN.md@@ -13,9 +13,7 @@ _Nothing currently parked — pick the next item from the Backlog._### Code quality / dedup (from `/simplify` passes)- [ ] [extract-mergeexpandintodraft-draft-result-from] **Extract `mergeExpandIntoDraft(draft, result)` from `UniverseBuilder.jsx#handleExpand`.** The function is ~150 lines mixing pure-merge logic (categories, sheets, canon, locks) with I/O shell (API call, setDraft, auto-save, toast). Pull the merge into a top-level pure helper so the I/O surface shrinks and the merge is unit-testable. Deferred from Phase B `/simplify` to keep that PR tightly scoped.-- [ ] [extract-useswipenav-hook-lib-clipboard-js] **Extract `useSwipeNav` from `MediaLightbox`.** Clipboard half of the original entry already shipped (`client/src/lib/clipboard.js`); `client/src/hooks/useSwipeNav.js` also exists for the swipe pattern but `MediaLightbox` still inlines its own swipe state. Migrate `MediaLightbox` swipe to `useSwipeNav` so the lightbox + any future mobile-swipe surface share one hook.- [ ] [route-medialightbox-settings-drawer-through] **Route `MediaLightbox` settings drawer through `components/Drawer.jsx`.** Reconcile `Drawer`'s flat Esc handler with the lightbox's layered Escape cascade.-- [ ] [apicore-request-arraybuffer-response-type] **Add an `arraybuffer` responseType escape hatch to `apiCore.request()`.** Two TTS audition helpers (`client/src/services/apiVoice.js#testTts` and `client/src/services/apiPipeline.js#previewPipelineTtsVoice`) currently bypass `request()` and do raw `fetch` because the shared helper assumes JSON. Collapsing both onto `request(endpoint, { ..., responseType: 'arraybuffer' })` would drop ~25 LOC of duplicated error-shaping + dedupe the path. Surfaced by /simplify during `[voice-picker-on-character-cards-voiceid-binding]`; deferred to keep that PR scoped to the picker. Not blocked on anything.- [ ] [extract-usependinglistrows-hook] **Extract `usePendingListRows({ persisted, requiredColumn, idPrefix, onChange }) → { merged, isPending, addRow, updateRow, removeRow }`.** Surfaced by /simplify during `[wardroberow-migrate-to-userowdraft]`. `WardrobeSection` in `client/src/components/pipeline/CanonCard.jsx:155-211` and `CharacterDetailEditor` list-section block in `client/src/components/universe/CharacterDetailEditor.jsx:202-278` now share substantial structure: pending rows held client-side until a required column fills, then promoted to `onChange`/`patchList`, with an index space that concatenates `[...persisted, ...pending]` and an `isPending(idx)` partition. Estimated ~70 LOC savings across both call sites. Two load-bearing details to preserve in the extraction: (1) `WardrobeSection` mints `wd-<uuid>` ids that round-trip verbatim; `CharacterDetailEditor` mints `pending-<key>-<uuid>` that get stripped at promotion — pass an `idPrefix` and a `stripIdOnPromote` flag (or unify both onto server-shaped ids and drop the strip); (2) hook is per-list (one instance per `LIST_SECTION` in `CharacterDetailEditor`, one in `WardrobeSection`), NOT per-component. Deferred to keep this PR focused on the `useRowDraft` migration; revisit when a third caller appears or the parallel divergence drifts.- [ ] [client-tests-for-deep-routing-drag-smoke-tests-for] **Client tests for deep routing + drag.** Smoke tests for `goToWorld(id)` URL transitions and chip-reorder ordering (mock `useSortable`).- [ ] [sweep-provider-type-tui-inline-checks-in-client] **Sweep `provider.type === 'tui'` inline checks in client.** New `isTuiProvider` helper in `client/src/utils/providers.js` not yet adopted in `client/src/pages/AIProviders.jsx` (3 remaining inline checks at lines 262, 396, 421 of CONFIG-style chips) and `client/src/components/cos/TaskAddForm.jsx`. Low priority — these are visual chip predicates, not behavioral.diff --git a/client/src/services/apiCore.js b/client/src/services/apiCore.jsindex 4514b6045b..4f256bf623 100644--- a/client/src/services/apiCore.js+++ b/client/src/services/apiCore.js@@ -6,7 +6,7 @@ export const API_BASE = '/api'; // exported for sub-modules that use fetch() direxport const PORTOS_APP_ID = 'portos-default';export async function request(endpoint, options = {}) {- const { silent, ...fetchOptions } = options;+ const { silent, responseType, ...fetchOptions } = options;const url = `${API_BASE}${endpoint}`;// Skip the JSON content-type header for FormData bodies — the browser must// set `multipart/form-data; boundary=…` itself, and any pre-supplied value@@ -55,6 +55,10 @@ export async function request(endpoint, options = {}) {return null;}+ if (responseType === 'arraybuffer') {+ return response.arrayBuffer();+ }+return response.json();}diff --git a/client/src/services/apiPipeline.js b/client/src/services/apiPipeline.jsindex 1bce547d66..a97c775b2b 100644--- a/client/src/services/apiPipeline.js+++ b/client/src/services/apiPipeline.js@@ -406,24 +406,16 @@ export const pipelineAutoRunSseUrl = (issueId) =>export const listPipelineTtsVoices = () => request('/pipeline/tts/voices', { silent: true });// Audition a voice — returns the rendered WAV as an ArrayBuffer so callers-// can feed it to `playWav` from voiceClient. Uses raw fetch because the-// shared `request()` helper auto-parses JSON. Optional `text` overrides the-// server-side default preview line.-export const previewPipelineTtsVoice = async (voiceId, text) => {- const res = await fetch('/api/pipeline/tts/preview', {+// can feed it to `playWav` from voiceClient. Optional `text` overrides the+// server-side default preview line. Silent — VoicePicker owns its own+// inline error toast.+export const previewPipelineTtsVoice = (voiceId, text) =>+ request('/pipeline/tts/preview', {method: 'POST',- headers: { 'Content-Type': 'application/json' },body: JSON.stringify(text ? { voiceId, text } : { voiceId }),+ responseType: 'arraybuffer',+ silent: true,});- if (!res.ok) {- const err = await res.json().catch(() => ({ error: `HTTP ${res.status}` }));- const e = new Error(err.error || 'Preview failed');- e.code = err.code;- e.status = res.status;- throw e;- }- return res.arrayBuffer();-};// Walks storyboards.scenes[].dialogue and populates stages.audio.lines[].// Pass { force: true } to replace existing lines wholesale (server defaultsdiff --git a/client/src/services/apiVoice.js b/client/src/services/apiVoice.jsindex 668b768b00..125d9e71be 100644--- a/client/src/services/apiVoice.js+++ b/client/src/services/apiVoice.js@@ -9,18 +9,10 @@ export const fetchPiperVoice = (voice) => api.post('/voice/piper/fetch', { voice// Returns the raw WAV bytes of the test utterance. Optional `voice` and// `engine` overrides let the voice-picker preview audition a voice from a// different engine than the saved one — without forcing a save first.-export const testTts = async (text, voice, engine) => {+// Silent — VoiceTab callers own their own error toasts.+export const testTts = (text, voice, engine) => {const body = { text };if (voice) body.voice = voice;if (engine) body.engine = engine;- const res = await fetch('/api/voice/test', {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify(body),- });- if (!res.ok) {- const err = await res.json().catch(() => ({ error: `HTTP ${res.status}` }));- throw new Error(err.error || 'TTS test failed');- }- return res.arrayBuffer();+ return api.post('/voice/test', body, { responseType: 'arraybuffer', silent: true });};