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: tell a provider failure apart from "nothing to ask" on taste Go deeper (#2733)
[._.]/ Adam Eivyb98d1ef142ef
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 04026dd594..4dc816a57d 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -39,6 +39,7 @@- **Every toast crashed when PortOS was reached over plain HTTP.** Toast ids were minted with `crypto.randomUUID()`, which browsers only expose on secure origins — so over Tailscale on `http://`, any toast threw `crypto.randomUUID is not a function`, including the error toasts meant to tell you a request had failed. Ids now come from a shared `uuidv4()` helper that falls back to `crypto.getRandomValues` (available on insecure origins) and still yields a spec-valid v4. This is what produced the `crypto.randomUUID` alerts in the Review Hub — it was PortOS's own bug, not an extension, so it is deliberately still reported.- [issue-2669] The LoRAs and Media Models screens no longer double-report a failure — the custom-catch callers now pass `{ silent: true }` so only their own message fires, not the shared `request()` helper's default toast too. Swept the LoRAs/media-models area: the Civitai suggestions refresh, LoRA delete, and the Civitai API-key save/clear now show a single toast, and the two list loads (LoRAs, Media Models) that already render a persistent inline error panel no longer also fire a toast saying the same thing. Threaded a backward-compatible `options` arg into the affected API wrappers (`listLorasFull`, `getCivitaiSuggestions`, `deleteLoraFull`, `setCivitaiAuth`, `clearCivitaiAuth`, `listCachedModels`).- [issue-2669] The Digital Twin screens no longer double-report a failure. A failed "Check for contradictions" on the Overview tab showed a toast *and* the same message inline in the results panel — it now reports once, inline. A failed Taste section reset no longer claims "Section reset" on top of the error. And when "Go deeper" fails outright, it now reports the actual reason instead of also claiming you need to complete more identity documents — that hint is now reserved for when it genuinely had nothing to ask.+- [issue-2733] **Taste "Go deeper" now tells the truth when the AI provider is the thing that failed.** A provider timeout, a rejected API key, or a model that answered with nothing came back looking exactly like "there's nothing to ask you" — so you were told to go complete more identity documents, while the real reason flashed past in a second toast. The two outcomes are now distinguished at the source: a provider failure reports once, naming the actual reason, and the identity-documents hint is finally reserved for a genuine lack of context (completing what [issue-2669] started, which could only separate outright request failures). A missing AI provider or an unsupported section now say so in their own words instead of borrowing that hint, and an empty answer from a provider is treated as the failure it is rather than being reported as a completed call.- Saving Digital Twin settings no longer leaves the Save button stuck on "Saving..." forever when the save fails — it re-enables so you can retry.- [issue-2669] Sharing, Messages, and Calendar screens no longer show two stacked error toasts when a share/subscribe/export/save/sync action fails — the custom-catch callers now pass `{ silent: true }` so only their own toast fires, not the shared `request()` helper's default one too. Swept the Messages/calendar/sharing feature area (both ConfigTabs, InboxTab, ReviewTab, ShareToButton, and the Sharing page) and threaded a backward-compatible `options` arg into the affected API wrappers (`evaluateMessages`, `enableGmailApi`, `getGoogleAuthUrl`, `create/updateMessageAccount`, `create/updateCalendarAccount`, `updateSubcalendars`, `saveGoogleAuthCredentials`, `start/runGoogleAutoConfig`, `confirmDailyReviewEvent`).- Creative Director projects that use the Antigravity provider no longer get stuck on "Planning." The agent now reliably receives its instructions instead of launching and sitting idle at an empty prompt (it waits for Antigravity's input box to be ready before sending, the same way the Claude provider does), so planning actually runs to completion.diff --git a/client/src/components/digital-twin/tabs/TasteTab.jsx b/client/src/components/digital-twin/tabs/TasteTab.jsxindex 30fadfaeed..6ac5d47444 100644--- a/client/src/components/digital-twin/tabs/TasteTab.jsx+++ b/client/src/components/digital-twin/tabs/TasteTab.jsx@@ -51,6 +51,29 @@ const SECTION_COLORS = {const NO_API_PROVIDER_TOAST = 'No API provider configured — open AI Providers to add one (e.g. LM Studio, OpenAI).';const NO_API_PROVIDER_TITLE = 'Configure an AI provider to enable';+// "Go deeper" came back with no question. Each `reason` names the precondition that+// was actually missing, so only a genuine lack of identity context points the user at+// their documents (#2733) — the other reasons aren't about documents at all.+const NO_QUESTION_TOAST = {+ 'no-context': 'No personalized question available — try completing more identity documents',+ 'no-provider': NO_API_PROVIDER_TOAST,+ 'unknown-section': 'This section doesn\'t support personalized questions.'+};+const NO_QUESTION_FALLBACK_TOAST = 'No personalized question available right now.';++export const noQuestionToast = (reason) => NO_QUESTION_TOAST[reason] || NO_QUESTION_FALLBACK_TOAST;++/**+ * Whether "Go deeper" must report a failed request itself.+ *+ * A provider failure (502 `AI_PROVIDER_ERROR`) is already announced by the `ai:status`+ * error toast with the provider's real reason, so that toast is the single voice for it.+ * Everything else — validation, 500, network drop — has no other reporter (the request+ * is sent `{ silent: true }`), so this component is its single voice. Exactly one layer+ * speaks either way (#2733, #2669).+ */+export const shouldReportGoDeeperError = (err) => err?.code !== 'AI_PROVIDER_ERROR';+export default function TasteTab({ onRefresh }) {const [profile, setProfile] = useState(null);const [loading, setLoading] = useState(true);@@ -161,31 +184,30 @@ export default function TasteTab({ onRefresh }) {return;}setLoadingPersonalized(true);- // Sentinel: `undefined` = the request itself failed (validation/500/network)- // and request() already toasted the true reason, so the hint below must not- // fire on top of it and misattribute the cause. `null` = the endpoint 200'd- // with an empty body, which is the genuine "nothing to ask" case.- //- // Caveat: a *provider* failure (timeout, upstream 401, empty completion)- // also arrives as 200-null, because generatePersonalizedTasteQuestion- // returns null on result.error and the route bare-res.json()s it — so the- // hint can still misattribute that one. Fixing it needs a server-side- // signal that separates "provider failed" from "nothing to ask"; tracked- // separately (#2733), since ai:status already toasts provider errors- // and a naive throw would just re-create the double toast.- const question = await api.getPersonalizedTasteQuestion(+ // Sentinel: `undefined` = the request failed and has already been reported (see+ // shouldReportGoDeeperError). A 200 always resolves to `{ question, reason }`, so a+ // missing question names its own cause instead of being guessed at here (#2733).+ // The request is silenced so that reporting stays a single layer's job.+ const result = await api.getPersonalizedTasteQuestion(activeSection,selectedProvider.providerId,- selectedProvider.model- ).catch(() => undefined);+ selectedProvider.model,+ { silent: true }+ ).catch((err) => {+ if (shouldReportGoDeeperError(err)) {+ toast.error(err?.message || 'Failed to generate a personalized question');+ }+ return undefined;+ });- if (question === undefined) {+ if (result === undefined) {setLoadingPersonalized(false);return;}+ const { question, reason } = result || {};if (!question) {- toast('No personalized question available — try completing more identity documents', { icon: '⚠️' });+ toast(noQuestionToast(reason), { icon: '⚠️' });setLoadingPersonalized(false);return;}diff --git a/client/src/components/digital-twin/tabs/TasteTab.test.jsx b/client/src/components/digital-twin/tabs/TasteTab.test.jsxnew file mode 100644index 0000000000..4e3f0809de--- /dev/null+++ b/client/src/components/digital-twin/tabs/TasteTab.test.jsx@@ -0,0 +1,38 @@+import { describe, it, expect } from 'vitest';+import { noQuestionToast, shouldReportGoDeeperError } from './TasteTab.jsx';++describe('TasteTab "Go deeper" reporting', () => {+ describe('noQuestionToast', () => {+ it('points at identity documents only for a genuine lack of context', () => {+ expect(noQuestionToast('no-context')).toMatch(/identity documents/);+ });++ it('does not blame identity documents for a missing provider or unknown section', () => {+ // Both were previously served the documents hint even though neither is about+ // documents — the misattribution this reason map exists to end (#2733).+ expect(noQuestionToast('no-provider')).not.toMatch(/identity documents/);+ expect(noQuestionToast('no-provider')).toMatch(/API provider/);+ expect(noQuestionToast('unknown-section')).not.toMatch(/identity documents/);+ });++ it('falls back to a neutral message for an unrecognized or absent reason', () => {+ // A newer server could name a reason this client build has no copy for; it must+ // degrade to something neutral rather than to the documents hint.+ expect(noQuestionToast('reason-from-a-newer-server')).toBe(noQuestionToast(undefined));+ expect(noQuestionToast(undefined)).not.toMatch(/identity documents/);+ });+ });++ describe('shouldReportGoDeeperError', () => {+ it('stays silent for a provider failure, which ai:status already toasts', () => {+ // Reporting here too would restore the double toast #2669 removed.+ expect(shouldReportGoDeeperError({ code: 'AI_PROVIDER_ERROR', message: 'Provider returned 401' })).toBe(false);+ });++ it('reports every other failure, which has no other voice once the request is silenced', () => {+ expect(shouldReportGoDeeperError({ code: 'VALIDATION_ERROR', message: 'bad section' })).toBe(true);+ expect(shouldReportGoDeeperError({ message: 'Server unreachable' })).toBe(true);+ expect(shouldReportGoDeeperError(undefined)).toBe(true);+ });+ });+});diff --git a/client/src/services/apiDigitalTwin.js b/client/src/services/apiDigitalTwin.jsindex 6705205e18..537d435ecc 100644--- a/client/src/services/apiDigitalTwin.js+++ b/client/src/services/apiDigitalTwin.js@@ -239,10 +239,11 @@ export const generateTasteSummary = (providerId, model, section) => request('/dimethod: 'POST',body: JSON.stringify({ providerId, model, ...(section ? { section } : {}) })});-export const getPersonalizedTasteQuestion = (section, providerId, model) =>+export const getPersonalizedTasteQuestion = (section, providerId, model, options = {}) =>request(`/digital-twin/taste/${section}/personalized-question`, {method: 'POST',- body: JSON.stringify({ providerId, model })+ body: JSON.stringify({ providerId, model }),+ ...options});export const resetTasteSection = (section) => request(`/digital-twin/taste/${section}`, {method: 'DELETE'diff --git a/server/lib/aiProvider.js b/server/lib/aiProvider.jsindex 1a630fee11..2ef529df62 100644--- a/server/lib/aiProvider.js+++ b/server/lib/aiProvider.js@@ -175,6 +175,13 @@ async function postChatCompletion(provider, model, prompt, { temperature, max_toif (typeof content !== 'string') {return { error: 'Provider returned a malformed (non-JSON or unexpected) response body' };}+ // An empty/whitespace-only completion is unusable output, not a successful call —+ // same class as the malformed body above. Classifying it here keeps the `ai:status`+ // stream honest (a call that produced nothing must not report "done") and gives+ // callers a single "the provider failed" signal to test: `result.error`.+ if (!content.trim()) {+ return { error: 'Provider returned an empty completion' };+ }// OpenAI-compatible bodies report token counts under `usage`; surface the completion// token count so the AI Core landmark can size its activity beam by output volume// (tokens/sec). Absent on some providers — callers treat a missing count as "unknown".diff --git a/server/lib/aiProvider.test.js b/server/lib/aiProvider.test.jsindex 22b93a3296..def8cd6081 100644--- a/server/lib/aiProvider.test.js+++ b/server/lib/aiProvider.test.js@@ -1,5 +1,18 @@-import { describe, it, expect } from 'vitest';-import { stripCodeFences, parseLLMJSON } from './aiProvider.js';+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import { stripCodeFences, parseLLMJSON, callProviderAISimple } from './aiProvider.js';++// `statusOp` is hoisted with the mock factories so the ai:status spy is in scope+// when vitest lifts vi.mock above the imports.+const { statusOp } = vi.hoisted(() => ({+ statusOp: { update: vi.fn(), complete: vi.fn(), error: vi.fn() },+}));++vi.mock('../services/providers.js', () => ({ getAllProviders: vi.fn() }));+vi.mock('../services/aiStatusEvents.js', () => ({ startAIOp: vi.fn(() => statusOp) }));+vi.mock('../services/ollamaManager.js', () => ({+ ensureProviderReady: vi.fn(),+ isOllamaProvider: vi.fn(() => false),+}));describe('aiProvider pure helpers', () => {describe('stripCodeFences', () => {@@ -68,3 +81,50 @@ describe('aiProvider pure helpers', () => {});});});++describe('callProviderAISimple completion classification', () => {+ // Keyless so the endpoint guard (which only gates API-key calls) stays out of the way.+ const provider = { id: 'provider-1', name: 'Example Provider', type: 'api', endpoint: 'https://api.example.com/v1' };++ const respondWith = (body) => vi.stubGlobal('fetch', vi.fn(async () => ({+ ok: true,+ status: 200,+ text: async () => JSON.stringify(body),+ })));++ const call = () => callProviderAISimple(provider, 'model-1', 'a prompt', { op: 'test-op', opLabel: 'Testing' });++ beforeEach(() => {+ statusOp.update.mockClear();+ statusOp.complete.mockClear();+ statusOp.error.mockClear();+ });++ afterEach(() => {+ vi.unstubAllGlobals();+ });++ it('classifies a whitespace-only completion as a provider error, not a successful call', async () => {+ respondWith({ choices: [{ message: { content: ' \n ' } }] });++ const result = await call();++ expect(result.error).toMatch(/empty completion/i);+ expect(result.text).toBeUndefined();+ // `ai:status` phase error is the single voice for provider failures, so a call+ // that produced nothing usable must reach it rather than reporting "done" (#2733).+ expect(statusOp.error).toHaveBeenCalledTimes(1);+ expect(statusOp.complete).not.toHaveBeenCalled();+ });++ it('reports a usable completion as success', async () => {+ respondWith({ choices: [{ message: { content: 'a real answer' } }] });++ const result = await call();++ expect(result).toMatchObject({ text: 'a real answer' });+ expect(result.error).toBeUndefined();+ expect(statusOp.complete).toHaveBeenCalledTimes(1);+ expect(statusOp.error).not.toHaveBeenCalled();+ });+});diff --git a/server/routes/digital-twin/taste.js b/server/routes/digital-twin/taste.jsindex ab91a2fc8b..29622538f7 100644--- a/server/routes/digital-twin/taste.js+++ b/server/routes/digital-twin/taste.js@@ -115,8 +115,11 @@ router.post('/taste/:section/personalized-question', asyncHandler(async (req, re});}const { providerId, model } = validateRequest(tastePersonalizedQuestionInputSchema, req.body);- const question = await tasteService.generatePersonalizedTasteQuestion(parsed.data, providerId, model);- res.json(question);+ // `{ question, reason }` — a provider failure throws (502 AI_PROVIDER_ERROR) and+ // bubbles to the error middleware, so a 200 here always means "we asked, and this+ // is the answer": either a question, or a `reason` naming what was missing.+ const result = await tasteService.generatePersonalizedTasteQuestion(parsed.data, providerId, model);+ res.json(result);}));/**diff --git a/server/services/taste-questionnaire.js b/server/services/taste-questionnaire.jsindex eaf9764f36..a480d6be0f 100644--- a/server/services/taste-questionnaire.js+++ b/server/services/taste-questionnaire.js@@ -12,6 +12,7 @@ import { join } from 'path';import { v4 as uuidv4 } from '../lib/uuid.js';import { atomicWrite, ensureDir, safeJSONParse, PATHS } from '../lib/fileUtils.js';import { resolveAPIProvider, callProviderAISimple } from '../lib/aiProvider.js';+import { ServerError } from '../lib/errorHandler.js';import { buildPrompt } from './promptService.js';import { digitalTwinEvents } from './digital-twin.js';@@ -887,16 +888,29 @@ async function aggregateIdentityContext(sectionId) {/*** Generate a personalized follow-up question for a taste section using LLM.+ *+ * Returns `{ question, reason }` — never a bare null. A failed provider call and+ * a legitimate "there is nothing to ask" are different outcomes and must not+ * collapse into the same value (#2733):+ *+ * - `{ question, reason: null }` — success.+ * - `{ question: null, reason: <why> }` — nothing to ask. `reason` names which+ * precondition was missing so the caller can explain the right thing instead of+ * blaming the user's identity documents for every empty result.+ * - throws `ServerError` (`AI_PROVIDER_ERROR`) — the provider call itself failed.+ * `callProviderAISimple` has already emitted `ai:status` phase `error` carrying+ * the real reason, so that toast is the single voice for this case and the+ * client silences `request()`'s own toast. Do not add a second reporter here.*/export async function generatePersonalizedTasteQuestion(sectionId, providerId, model) {const config = TASTE_SECTIONS[sectionId];- if (!config) return null;+ if (!config) return { question: null, reason: 'unknown-section' };const { context, sourcesUsed } = await aggregateIdentityContext(sectionId);- if (!context) return null;+ if (!context) return { question: null, reason: 'no-context' };const provider = await resolveAPIProvider(providerId);- if (!provider) return null;+ if (!provider) return { question: null, reason: 'no-provider' };const modelId = model || provider.defaultModel;@@ -931,21 +945,29 @@ Generate exactly ONE question. Do not include any preamble, numbering, or explanopLabel: `Crafting a deeper ${config.label} question`});- if (result.error || !result.text?.trim()) {- console.log(`🎨 Personalized question generation failed for ${sectionId}: ${result.error || 'empty response'}`);- return null;+ // `result.error` is the one provider-failure signal — an empty completion is+ // classified as an error by callProviderAISimple, so it arrives here too.+ if (result.error) {+ console.log(`🎨 Personalized question generation failed for ${sectionId}: ${result.error}`);+ throw new ServerError(`Personalized question generation failed: ${result.error}`, {+ status: 502,+ code: 'AI_PROVIDER_ERROR'+ });}const questionId = `${sectionId}-p25-${uuidv4()}`;console.log(`🎨 Personalized question generated for ${sectionId} (${sourcesUsed.length} sources)`);return {- questionId,- text: result.text.trim(),- isPersonalized: true,- identityContextUsed: sourcesUsed,- section: sectionId,- sectionLabel: config.label+ question: {+ questionId,+ text: result.text.trim(),+ isPersonalized: true,+ identityContextUsed: sourcesUsed,+ section: sectionId,+ sectionLabel: config.label+ },+ reason: null};}diff --git a/server/services/taste-questionnaire.test.js b/server/services/taste-questionnaire.test.jsindex 437c47c0fd..6dac1e8077 100644--- a/server/services/taste-questionnaire.test.js+++ b/server/services/taste-questionnaire.test.js@@ -21,6 +21,14 @@ vi.mock('./digital-twin.js', () => ({digitalTwinEvents: { emit: vi.fn() },}));+// Drive the provider boundary directly so each "Go deeper" outcome is reachable+// without a live LLM. Re-imported per test because beforeEach resets the module+// registry, which mints fresh spies for each generation.+vi.mock('../lib/aiProvider.js', () => ({+ resolveAPIProvider: vi.fn(),+ callProviderAISimple: vi.fn(),+}));+beforeEach(() => {vi.resetModules();});@@ -102,3 +110,81 @@ describe('getNextQuestion progress', () => {expect(next.progress.totalAnswered).toBe(0);});});++describe('generatePersonalizedTasteQuestion outcomes', () => {+ const PROVIDER = { id: 'provider-1', name: 'Example Provider', defaultModel: 'model-1' };++ // Identity context is aggregated partly from *other* sections' taste responses, so+ // answering in `food` is enough to make a `movies` question well-founded.+ const seedIdentityContext = (taste) =>+ taste.submitAnswer('food', 'food-core-1', 'Sichuan and Thai, the hotter the better');++ const clearIdentityContext = async (taste) => {+ for (const sectionId of Object.keys(taste.TASTE_SECTIONS)) {+ await taste.resetSection(sectionId);+ }+ };++ it('reports no-context — the one outcome that is really about missing documents', async () => {+ const taste = await import('./taste-questionnaire.js');+ await clearIdentityContext(taste);++ expect(await taste.generatePersonalizedTasteQuestion('movies')).toEqual({+ question: null,+ reason: 'no-context',+ });+ });++ it('reports unknown-section rather than borrowing the missing-documents reason', async () => {+ const taste = await import('./taste-questionnaire.js');++ expect(await taste.generatePersonalizedTasteQuestion('not-a-real-section')).toEqual({+ question: null,+ reason: 'unknown-section',+ });+ });++ it('reports no-provider rather than blaming the user documents that do exist', async () => {+ const { resolveAPIProvider } = await import('../lib/aiProvider.js');+ resolveAPIProvider.mockResolvedValue(null);+ const taste = await import('./taste-questionnaire.js');+ await seedIdentityContext(taste);++ expect(await taste.generatePersonalizedTasteQuestion('movies')).toEqual({+ question: null,+ reason: 'no-provider',+ });+ });++ it('throws AI_PROVIDER_ERROR instead of collapsing a provider failure into "nothing to ask"', async () => {+ const { resolveAPIProvider, callProviderAISimple } = await import('../lib/aiProvider.js');+ resolveAPIProvider.mockResolvedValue(PROVIDER);+ callProviderAISimple.mockResolvedValue({ error: 'Provider returned 401: invalid key' });+ const taste = await import('./taste-questionnaire.js');+ await seedIdentityContext(taste);++ // Must reject — a 200-null here is exactly what made a provider failure look+ // like "you haven't written enough identity documents" (#2733).+ await expect(taste.generatePersonalizedTasteQuestion('movies')).rejects.toMatchObject({+ code: 'AI_PROVIDER_ERROR',+ status: 502,+ message: expect.stringContaining('invalid key'),+ });+ });++ it('returns the question with reason null on success', async () => {+ const { resolveAPIProvider, callProviderAISimple } = await import('../lib/aiProvider.js');+ resolveAPIProvider.mockResolvedValue(PROVIDER);+ callProviderAISimple.mockResolvedValue({ text: ' Which film would you rewatch forever? ' });+ const taste = await import('./taste-questionnaire.js');+ await seedIdentityContext(taste);++ const result = await taste.generatePersonalizedTasteQuestion('movies');+ expect(result.reason).toBeNull();+ expect(result.question).toMatchObject({+ text: 'Which film would you rewatch forever?',+ isPersonalized: true,+ section: 'movies',+ });+ });+});