From 9382a121373c4c8325148281a157e839ecfd1f2e Mon Sep 17 00:00:00 2001 From: RainbowBird Date: Sun, 7 Jun 2026 20:31:22 +0800 Subject: [PATCH] chore: cleanup and lint fix --- .../docs/ai-context/admin-flux-grants.md | 6 +- .../ai-context/verifications/streaming-tts.md | 2 +- apps/server/scripts/e2e-llm-router.ts | 26 +- apps/server/src/utils/envelope-crypto.test.ts | 1 + .../desktop-overlay-live-window-smoke.ts | 15 +- .../src/main/app/file-logger.ts | 3 +- .../services/airi/widgets/artistry-bridge.ts | 8 +- .../main/services/electron/auto-updater.ts | 5 +- .../src/main/windows/desktop-overlay/index.ts | 5 +- .../desktop-overlay/rpc/index.electron.ts | 3 +- .../stage-islands/controls-island/index.vue | 7 +- .../renderer/pages/desktop-overlay-polling.ts | 4 +- .../src/renderer/pages/desktop-overlay.vue | 4 +- .../src/renderer/stores/chat-sync.ts | 3 +- .../stores/tools/builtin/image-journal.ts | 6 +- .../widgets/artistry/components/Comfy.vue | 2 +- .../pages/devtools/model-driver-mediapipe.vue | 5 +- docs/ai/context/verification-automation.md | 2 +- ...001-feat-observability-diagnostics-plan.md | 283 ++++++++++++++++++ packages/audio/src/audio-context/index.ts | 4 +- .../src/audio-context/processor.worklet.ts | 6 +- packages/audio/src/utils/error-message.ts | 17 ++ packages/cap-vite/package.json | 1 + packages/cap-vite/src/bin/run.ts | 3 +- packages/cap-vite/src/utils/error-message.ts | 17 ++ packages/cap-vite/src/vite-plugin.ts | 3 +- .../core-agent/src/runtime/llm-service.ts | 5 +- .../core-agent/src/utils/error-message.ts | 17 ++ packages/i18n/src/locales/ja/settings.yaml | 4 +- .../tasks/error-message.ts | 17 ++ .../tasks/prepare-tasks.ts | 3 +- .../src/managers/playback-manager.ts | 4 +- .../src/utils/error-message.ts | 17 ++ packages/plugin-sdk/package.json | 1 + packages/plugin-sdk/src/plugin-host/core.ts | 5 +- .../plugin-sdk/src/utils/error-message.ts | 17 ++ .../platforms/macos-26/texts/index.ts | 0 .../components/platforms/windows-11/index.ts | 0 .../src/components/Layouts/HeaderAvatar.vue | 4 +- .../src/pages/devtools/plugin-host.vue | 15 +- ...ders-transcription-realtime-aliyun-nls.vue | 7 +- .../account/account-settings-page.vue | 4 +- .../components/CardCreationDialog.vue | 2 +- .../airi-card/components/CardDetailDialog.vue | 13 +- .../src/pages/settings/modules/hearing.vue | 7 +- .../pages/settings/providers/chat/ollama.vue | 3 +- .../providers/speech/mimo-audio-speech.vue | 14 +- .../aliyun-nls-transcription.vue | 7 +- .../transcription/browser-web-speech-api.vue | 3 +- .../src/pages/settings/scene/index.vue | 13 +- packages/stage-shared/src/error-message.ts | 18 ++ .../src/utils/live2d-structure-report.ts | 34 ++- .../src/components/scenes/spine/Model.vue | 2 +- .../stage-ui-spine/src/utils/spine-preview.ts | 3 +- .../chat/components/action-menu/index.vue | 5 +- .../model-selector/Live2DReportModal.vue | 6 +- .../dialogs/onboarding/onboarding.vue | 10 +- .../speech-playground-openai-compatible.vue | 3 +- .../scenarios/providers/speech-playground.vue | 3 +- .../providers/transcription-playground.vue | 5 +- .../src/composables/audio/audio-analyzer.ts | 3 +- packages/stage-ui/src/composables/whisper.ts | 3 +- packages/stage-ui/src/libs/auth-config.ts | 2 +- .../inference/adapters/background-removal.ts | 4 +- .../src/libs/inference/adapters/kokoro.ts | 4 +- .../src/libs/inference/adapters/whisper.ts | 4 +- .../stage-ui/src/libs/inference/protocol.ts | 5 +- .../src/libs/inference/worker-manager.ts | 4 +- packages/stage-ui/src/libs/workers/worker.ts | 5 +- packages/stage-ui/src/stores/ai/models/vad.ts | 3 +- .../src/stores/devtools/plugin-host-debug.ts | 3 +- .../src/stores/modules/artistry-autonomous.ts | 2 +- .../stage-ui/src/stores/modules/hearing.ts | 4 +- .../stores/providers/web-speech-api/index.ts | 4 +- packages/stage-ui/src/tools/mcp.ts | 4 +- .../src/workers/background-removal/worker.ts | 3 +- .../stage-ui/src/workers/kokoro/worker.ts | 5 +- packages/ui-loading-screens/package.json | 1 + .../components/LoadingSciFiCircle/index.vue | 4 +- .../src/utils/error-message.ts | 17 ++ .../airi-plugin-web-extension/package.json | 1 + .../src/background/client.ts | 6 +- .../src/utils/error-message.ts | 17 ++ pnpm-lock.yaml | 12 + .../chrome-extension/msg_bridge.js | 2 + .../src/bin/demo-hello-world.ts | 12 +- .../src/bin/e2e-airi-chat-observable.ts | 5 +- .../e2e-airi-chat-terminal-self-acquire.ts | 5 +- .../src/bin/e2e-airi-discord-agentic.ts | 7 +- .../src/bin/e2e-airi-discord-observable.ts | 5 +- services/computer-use-mcp/src/bin/runner.ts | 7 +- .../browser-dom/browser-repair-contract.ts | 4 +- .../src/browser-dom/cdp-bridge.ts | 6 +- .../src/desktop-grounding.test.ts | 1 - .../computer-use-mcp/src/desktop-grounding.ts | 32 +- .../src/executors/linux-x11.ts | 3 +- .../src/executors/macos-local.ts | 3 +- .../computer-use-mcp/src/runner/client.ts | 6 +- .../computer-use-mcp/src/runner/service.ts | 3 +- .../computer-use-mcp/src/runtime-probes.ts | 9 +- .../src/server/action-executor.ts | 5 +- .../src/server/cdp-manager.ts | 3 +- .../src/server/register-accessibility.ts | 9 +- .../src/server/register-cdp.ts | 25 +- .../src/server/register-chrome-session.ts | 3 +- .../server/register-desktop-grounding.test.ts | 5 +- .../src/server/register-desktop-grounding.ts | 3 +- .../src/server/register-display.ts | 9 +- .../src/server/register-pty.ts | 15 +- .../src/server/workflow-prep-tools.ts | 3 +- .../computer-use-mcp/src/snap-resolver.ts | 4 +- .../src/terminal/pty-runner.ts | 2 +- .../src/utils/error-message.ts | 18 ++ .../computer-use-mcp/src/utils/screenshot.ts | 3 +- .../computer-use-mcp/src/workflows/engine.ts | 11 +- .../conscious/js-planner-sandbox-runner.ts | 5 +- services/minecraft/src/debug/server.ts | 3 +- services/minecraft/src/debug/tool-executor.ts | 3 +- services/minecraft/src/utils/error-message.ts | 17 ++ .../src/adapters/airi-adapter.ts | 11 +- .../src/core/services/tweet.ts | 11 +- 121 files changed, 846 insertions(+), 264 deletions(-) create mode 100644 docs/plans/2026-06-07-001-feat-observability-diagnostics-plan.md create mode 100644 packages/audio/src/utils/error-message.ts create mode 100644 packages/cap-vite/src/utils/error-message.ts create mode 100644 packages/core-agent/src/utils/error-message.ts create mode 100644 packages/model-driver-mediapipe/tasks/error-message.ts create mode 100644 packages/pipelines-audio/src/utils/error-message.ts create mode 100644 packages/plugin-sdk/src/utils/error-message.ts delete mode 100644 packages/scenarios-stage-tamagotchi-browser/src/components/platforms/macos-26/texts/index.ts delete mode 100644 packages/scenarios-stage-tamagotchi-browser/src/components/platforms/windows-11/index.ts create mode 100644 packages/ui-loading-screens/src/utils/error-message.ts create mode 100644 plugins/airi-plugin-web-extension/src/utils/error-message.ts create mode 100644 services/computer-use-mcp/src/utils/error-message.ts create mode 100644 services/minecraft/src/utils/error-message.ts diff --git a/apps/server/docs/ai-context/admin-flux-grants.md b/apps/server/docs/ai-context/admin-flux-grants.md index 80a5df2c9..4c53da5fc 100644 --- a/apps/server/docs/ai-context/admin-flux-grants.md +++ b/apps/server/docs/ai-context/admin-flux-grants.md @@ -19,7 +19,7 @@ Auth:`authGuard` + `adminGuard`(`ADMIN_EMAILS` allowlist + 验证邮箱) Body: -```ts +```text { description: string, // 1..500 chars; 写入 flux_transaction.metadata.description amount: number, // 1..MAX_GRANT_AMOUNT_PER_USER (10_000), 单人发放数量 @@ -33,13 +33,13 @@ Body: dry-run 响应: -```ts +```text { preview: { totalEmails, willGrant, willSkip: { notFound, userDeleted, duplicateInInput }, totalFluxToIssue, samples } } ``` 实发响应: -```ts +```text { summary: { totalEmails, willGrant, willSkip, totalFluxToIssue, samples }, result: { diff --git a/apps/server/docs/ai-context/verifications/streaming-tts.md b/apps/server/docs/ai-context/verifications/streaming-tts.md index 948d5abb9..b373fe59f 100644 --- a/apps/server/docs/ai-context/verifications/streaming-tts.md +++ b/apps/server/docs/ai-context/verifications/streaming-tts.md @@ -208,7 +208,7 @@ reads `keys[0]`, so a write replaces the active key). The file `/tmp/smoke-streaming-tts.mjs` used in the smoke run: ```js -import WebSocket from '/node_modules/.pnpm/ws@*/node_modules/ws/wrapper.mjs' +import WebSocket from 'ws' const URL = 'ws://localhost:5933/v1/audio/speech/stream' diff --git a/apps/server/scripts/e2e-llm-router.ts b/apps/server/scripts/e2e-llm-router.ts index 6d2f8d74f..457c4f435 100644 --- a/apps/server/scripts/e2e-llm-router.ts +++ b/apps/server/scripts/e2e-llm-router.ts @@ -43,7 +43,7 @@ async function main() { // the router is actually sending when E2E fails. Remove after E2E passes. const debugFetch: typeof fetch = async (input, init) => { const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url - console.log(` fetch → POST ${url}`) + console.info(` fetch → POST ${url}`) if (init?.headers) { const hdrs = init.headers as Record const auth = hdrs.authorization || hdrs.Authorization @@ -51,16 +51,16 @@ async function main() { // Never log credential substrings: a 30-char prefix of an OpenRouter // key (`sk-or-v1-bb1a38505a7309...`) is enough to identify the account. // Print presence only. Source: codex review 2026-05-15 #10. - console.log(` auth = ${auth ? '' : ''}`) + console.info(` auth = ${auth ? '' : ''}`) } if (init?.body) { - console.log(` body = ${String(init.body).slice(0, 200)}`) + console.info(` body = ${String(init.body).slice(0, 200)}`) } const res = await fetch(input as any, init as any) if (!res.ok) { const clone = res.clone() const text = await clone.text().catch(() => '') - console.log(` ← ${res.status} body: ${text.slice(0, 300)}`) + console.info(` ← ${res.status} body: ${text.slice(0, 300)}`) } return res } @@ -72,7 +72,7 @@ async function main() { fetchImpl: debugFetch, }) - console.log('→ calling router.route() with model=chat-default') + console.info('→ calling router.route() with model=chat-default') const start = Date.now() let response: Response try { @@ -94,7 +94,7 @@ async function main() { } const elapsed = Date.now() - start - console.log(`← status ${response.status} (${elapsed}ms)`) + console.info(`← status ${response.status} (${elapsed}ms)`) if (!response.ok) { const text = await response.text() @@ -109,11 +109,11 @@ async function main() { model?: string } const content = payload.choices?.[0]?.message?.content - console.log() - console.log('Assistant response:') - console.log(` model: ${payload.model ?? ''}`) - console.log(` text: ${JSON.stringify(content)}`) - console.log(` tokens: prompt=${payload.usage?.prompt_tokens ?? '?'} completion=${payload.usage?.completion_tokens ?? '?'}`) + console.info() + console.info('Assistant response:') + console.info(` model: ${payload.model ?? ''}`) + console.info(` text: ${JSON.stringify(content)}`) + console.info(` tokens: prompt=${payload.usage?.prompt_tokens ?? '?'} completion=${payload.usage?.completion_tokens ?? '?'}`) if (!content) { console.error('error: response.choices[0].message.content was empty') @@ -121,8 +121,8 @@ async function main() { exit(1) } - console.log() - console.log('E2E PASS — router service successfully called OpenRouter and returned a usable response.') + console.info() + console.info('E2E PASS — router service successfully called OpenRouter and returned a usable response.') await redis.quit() } diff --git a/apps/server/src/utils/envelope-crypto.test.ts b/apps/server/src/utils/envelope-crypto.test.ts index 02e9d6182..440100649 100644 --- a/apps/server/src/utils/envelope-crypto.test.ts +++ b/apps/server/src/utils/envelope-crypto.test.ts @@ -1,3 +1,4 @@ +import { Buffer } from 'node:buffer' import { randomBytes } from 'node:crypto' import { describe, expect, it } from 'vitest' diff --git a/apps/stage-tamagotchi/scripts/desktop-overlay-live-window-smoke.ts b/apps/stage-tamagotchi/scripts/desktop-overlay-live-window-smoke.ts index 8712fd441..6ea6623fe 100644 --- a/apps/stage-tamagotchi/scripts/desktop-overlay-live-window-smoke.ts +++ b/apps/stage-tamagotchi/scripts/desktop-overlay-live-window-smoke.ts @@ -1,3 +1,4 @@ +import type { Buffer } from 'node:buffer' import type { ChildProcessWithoutNullStreams } from 'node:child_process' import { spawn } from 'node:child_process' @@ -8,6 +9,8 @@ import { dirname, resolve } from 'node:path' import { env, exit, kill as killProcess } from 'node:process' import { fileURLToPath } from 'node:url' +import { errorMessageFromValue } from '@proj-airi/stage-shared' + import { desktopOverlayPollHeartbeatMarker } from '../src/shared/desktop-overlay-heartbeat' import { selectDesktopOverlaySmokeCandidateId } from '../src/shared/desktop-overlay-live-window-smoke' @@ -478,14 +481,14 @@ async function main() { waitForRemoteDebug(debugPort), stageExited, ]).catch((error) => { - throw new Error(`APP_START_FAILED: ${error instanceof Error ? error.message : String(error)}`) + throw new Error(`APP_START_FAILED: ${errorMessageFromValue(error)}`) }) overlayClient = await Promise.race([ connectOverlayClient(debugPort), stageExited, ]).catch((error) => { - throw new Error(`APP_START_FAILED: ${error instanceof Error ? error.message : String(error)}`) + throw new Error(`APP_START_FAILED: ${errorMessageFromValue(error)}`) }) // NOTICE: @@ -499,7 +502,7 @@ async function main() { connectOverlayClient(debugPort), stageExited, ]).catch((error) => { - throw new Error(`APP_START_FAILED: ${error instanceof Error ? error.message : String(error)}`) + throw new Error(`APP_START_FAILED: ${errorMessageFromValue(error)}`) }) const readiness = await overlayClient.evaluate<{ state: 'booting' | 'ready' | 'degraded', error?: string }>('window.__AIRI_DESKTOP_OVERLAY_SMOKE__.getReadiness()') @@ -531,13 +534,13 @@ async function main() { assert(pointerIntent.candidateId === candidateId, `lastPointerIntent candidate mismatch: expected ${candidateId}, got ${String(pointerIntent.candidateId)}`) } catch (error) { - throw new Error(`MCP_CALL_FAILED: ${error instanceof Error ? error.message : String(error)}`) + throw new Error(`MCP_CALL_FAILED: ${errorMessageFromValue(error)}`) } const heartbeat = await waitFor('overlay poll heartbeat', () => { return heartbeatLines.find(line => line.includes('snapshotId=') && line.includes('pointerIntent=yes')) }, 30_000, 250).catch((error) => { - throw new Error(`HEARTBEAT_TIMEOUT: ${error instanceof Error ? error.message : String(error)}`) + throw new Error(`HEARTBEAT_TIMEOUT: ${errorMessageFromValue(error)}`) }) console.info(JSON.stringify({ @@ -556,7 +559,7 @@ async function main() { if (import.meta.main) { main().catch((error) => { - console.error(error instanceof Error ? error.message : String(error)) + console.error(errorMessageFromValue(error)) console.error(`stage log: ${stageLogPath}`) exit(1) }) diff --git a/apps/stage-tamagotchi/src/main/app/file-logger.ts b/apps/stage-tamagotchi/src/main/app/file-logger.ts index 29b5d162d..143228be0 100644 --- a/apps/stage-tamagotchi/src/main/app/file-logger.ts +++ b/apps/stage-tamagotchi/src/main/app/file-logger.ts @@ -25,6 +25,7 @@ import { mkdir, open, stat } from 'node:fs/promises' import { join } from 'node:path' +import { errorMessageFromValue } from '@proj-airi/stage-shared' import { app } from 'electron' // ============================================================================ @@ -71,7 +72,7 @@ export const nullFileLoggerHandle: FileLoggerHandle = { * Extracts a human-readable error message from an unknown error object. */ function getErrorMessage(error: unknown): string { - return error instanceof Error ? error.message : String(error) + return errorMessageFromValue(error) } /** diff --git a/apps/stage-tamagotchi/src/main/services/airi/widgets/artistry-bridge.ts b/apps/stage-tamagotchi/src/main/services/airi/widgets/artistry-bridge.ts index 3c9252a02..e19a2e292 100644 --- a/apps/stage-tamagotchi/src/main/services/airi/widgets/artistry-bridge.ts +++ b/apps/stage-tamagotchi/src/main/services/airi/widgets/artistry-bridge.ts @@ -12,11 +12,7 @@ import { createHash } from 'node:crypto' import { useLogg } from '@guiiai/logg' import { defineInvokeHandler } from '@moeru/eventa' import { errorMessageFrom } from '@moeru/std' -import { - artistryGenerateHeadless, - artistrySyncConfig, - artistryTestComfyUIConnection, -} from '@proj-airi/stage-shared' +import { artistryGenerateHeadless, artistrySyncConfig, artistryTestComfyUIConnection, errorMessageFromValue } from '@proj-airi/stage-shared' import { injeca } from 'injeca' import { ComfyUIProvider } from './providers/comfyui' @@ -256,7 +252,7 @@ export async function generateHeadless(params: { return await executionPromise } catch (err) { - return { error: errorMessageFrom(err) ?? String(err) } + return { error: errorMessageFromValue(err) } } finally { // Remove from map after completion so it can be re-triggered later diff --git a/apps/stage-tamagotchi/src/main/services/electron/auto-updater.ts b/apps/stage-tamagotchi/src/main/services/electron/auto-updater.ts index dfb44b49f..3002802aa 100644 --- a/apps/stage-tamagotchi/src/main/services/electron/auto-updater.ts +++ b/apps/stage-tamagotchi/src/main/services/electron/auto-updater.ts @@ -16,7 +16,8 @@ import semver from 'semver' import { is } from '@electron-toolkit/utils' import { useLogg } from '@guiiai/logg' import { defineInvokeHandler } from '@moeru/eventa' -import { errorMessageFrom, tryCatch } from '@moeru/std' +import { tryCatch } from '@moeru/std' +import { errorMessageFromValue } from '@proj-airi/stage-shared' import { committerDate } from '~build/git' import { app } from 'electron' import { Semaphore } from 'es-toolkit' @@ -335,7 +336,7 @@ export function setupAutoUpdater(options: AutoUpdaterOptions = {}): AutoUpdater function broadcastUpdaterError(error: unknown, reason: string) { broadcast({ status: 'error', - error: { message: errorMessageFrom(error) ?? String(error) }, + error: { message: errorMessageFromValue(error) }, }) log.withError(error).error(reason) } diff --git a/apps/stage-tamagotchi/src/main/windows/desktop-overlay/index.ts b/apps/stage-tamagotchi/src/main/windows/desktop-overlay/index.ts index 708407085..d1a2a8317 100644 --- a/apps/stage-tamagotchi/src/main/windows/desktop-overlay/index.ts +++ b/apps/stage-tamagotchi/src/main/windows/desktop-overlay/index.ts @@ -24,6 +24,7 @@ import type { ServerChannel } from '../../services/airi/channel-server' import type { McpStdioManager } from '../../services/airi/mcp-servers' import { join, resolve } from 'node:path' +import { env } from 'node:process' import { BrowserWindow, screen } from 'electron' @@ -38,7 +39,7 @@ import { /** Whether the desktop overlay feature is enabled */ export function isDesktopOverlayEnabled(): boolean { - return process.env.AIRI_DESKTOP_OVERLAY === '1' + return env.AIRI_DESKTOP_OVERLAY === '1' } /** @@ -47,7 +48,7 @@ export function isDesktopOverlayEnabled(): boolean { * mount the in-page smoke bridge. */ export function isDesktopOverlayPollHeartbeatEnabled(): boolean { - return process.env.AIRI_DESKTOP_OVERLAY_POLL_HEARTBEAT === '1' + return env.AIRI_DESKTOP_OVERLAY_POLL_HEARTBEAT === '1' } let overlayWindow: BrowserWindow | null = null diff --git a/apps/stage-tamagotchi/src/main/windows/desktop-overlay/rpc/index.electron.ts b/apps/stage-tamagotchi/src/main/windows/desktop-overlay/rpc/index.electron.ts index e5dcef419..357afc1e3 100644 --- a/apps/stage-tamagotchi/src/main/windows/desktop-overlay/rpc/index.electron.ts +++ b/apps/stage-tamagotchi/src/main/windows/desktop-overlay/rpc/index.electron.ts @@ -18,6 +18,7 @@ import type { DesktopOverlayReadiness } from './contracts' import { defineInvokeHandler } from '@moeru/eventa' import { createContext } from '@moeru/eventa/adapters/electron/main' +import { errorMessageFromValue } from '@proj-airi/stage-shared' import { ipcMain } from 'electron' import { getDesktopOverlayReadinessContract } from '../../../../shared/eventa' @@ -51,7 +52,7 @@ export async function setupDesktopOverlayElectronInvokes(params: { catch (error) { readiness = { state: 'degraded', - error: error instanceof Error ? error.message : String(error), + error: errorMessageFromValue(error), } // We intentionally don't throw here so the window still opens and // the renderer gracefully detects the degraded state via polling. diff --git a/apps/stage-tamagotchi/src/renderer/components/stage-islands/controls-island/index.vue b/apps/stage-tamagotchi/src/renderer/components/stage-islands/controls-island/index.vue index 1adc0c2a8..a9cc2bd02 100644 --- a/apps/stage-tamagotchi/src/renderer/components/stage-islands/controls-island/index.vue +++ b/apps/stage-tamagotchi/src/renderer/components/stage-islands/controls-island/index.vue @@ -47,7 +47,12 @@ const blockingOverlays = reactive(new Set()) const isBlocked = computed(() => blockingOverlays.size > 0) function setOverlay(key: string, active: boolean) { - active ? blockingOverlays.add(key) : blockingOverlays.delete(key) + if (active) { + blockingOverlays.add(key) + return + } + + blockingOverlays.delete(key) } // Expose for parent (e.g. to disable click-through when a dialog is open) diff --git a/apps/stage-tamagotchi/src/renderer/pages/desktop-overlay-polling.ts b/apps/stage-tamagotchi/src/renderer/pages/desktop-overlay-polling.ts index fd5b38180..6adf2e39d 100644 --- a/apps/stage-tamagotchi/src/renderer/pages/desktop-overlay-polling.ts +++ b/apps/stage-tamagotchi/src/renderer/pages/desktop-overlay-polling.ts @@ -7,6 +7,8 @@ import type { McpCallToolResult } from '@proj-airi/stage-ui/stores/mcp-tool-bridge' +import { errorMessageFromValue } from '@proj-airi/stage-shared' + import { desktopOverlayPollHeartbeatMarker, desktopOverlayPollHeartbeatQueryParam } from '../../shared/desktop-overlay-heartbeat' // --------------------------------------------------------------------------- @@ -265,7 +267,7 @@ export function createOverlayPollController(config: OverlayPollConfig): OverlayP } catch (e) { currentBootstrapState = 'degraded' - currentBootstrapError = e instanceof Error ? e.message : String(e) + currentBootstrapError = errorMessageFromValue(e) } if (!running) diff --git a/apps/stage-tamagotchi/src/renderer/pages/desktop-overlay.vue b/apps/stage-tamagotchi/src/renderer/pages/desktop-overlay.vue index e06e3d32c..bab7adfbb 100644 --- a/apps/stage-tamagotchi/src/renderer/pages/desktop-overlay.vue +++ b/apps/stage-tamagotchi/src/renderer/pages/desktop-overlay.vue @@ -173,7 +173,9 @@ const rippleStyle = computed(() => { watch(pointerPhase, (newPhase) => { if (newPhase === 'completed') { showRipple.value = true - setTimeout(() => { showRipple.value = false }, 600) + setTimeout(() => { + showRipple.value = false + }, 600) } }) diff --git a/apps/stage-tamagotchi/src/renderer/stores/chat-sync.ts b/apps/stage-tamagotchi/src/renderer/stores/chat-sync.ts index d1d70930c..3750d97ac 100644 --- a/apps/stage-tamagotchi/src/renderer/stores/chat-sync.ts +++ b/apps/stage-tamagotchi/src/renderer/stores/chat-sync.ts @@ -4,6 +4,7 @@ import type { ChatSessionMeta } from '@proj-airi/stage-ui/types/chat-session' import type { ChatProvider } from '@xsai-ext/providers/utils' import { errorMessageFrom } from '@moeru/std' +import { errorMessageFromValue } from '@proj-airi/stage-shared' import { useChatOrchestratorStore } from '@proj-airi/stage-ui/stores/chat' import { useChatMaintenanceStore } from '@proj-airi/stage-ui/stores/chat/maintenance' import { useChatSessionStore } from '@proj-airi/stage-ui/stores/chat/session-store' @@ -153,7 +154,7 @@ function logChatSyncError(message: string, error: unknown, details: Record { ) expect(responses.filter(r => r.status === 402)).toHaveLength(5) - const ledger = await ctx.db.query.fluxTransaction.findMany({ where: ... }) + const ledger = await ctx.db.query.fluxTransaction.findMany({ where: { userId: 'u1' } }) expect(ledger).toHaveLength(0) const metrics = await ctx.scrapeMetrics() diff --git a/docs/plans/2026-06-07-001-feat-observability-diagnostics-plan.md b/docs/plans/2026-06-07-001-feat-observability-diagnostics-plan.md new file mode 100644 index 000000000..f4755bb60 --- /dev/null +++ b/docs/plans/2026-06-07-001-feat-observability-diagnostics-plan.md @@ -0,0 +1,283 @@ +--- +title: "feat: Full-flow observability diagnostics" +status: active +date: 2026-06-07 +type: feat +--- + +# feat: Full-flow observability diagnostics + +## Summary + +Add a shared server-side diagnostics layer for OpenAI-compatible chat, HTTP TTS, streaming TTS WebSocket, router attempts, upstream adapters, billing, request logs, product events, logs, traces, and metrics. The immediate acceptance sample is the CosyVoice incident where AIRI returned 502 while UnSpeech/DashScope returned 400, but the implementation should cover the full generation flow rather than only TTS errors. + +## Problem Frame + +During the TTS incident, Grafana showed a concentrated burst of `POST /api/v1/audio/speech` 502 responses for `alibaba/cosyvoice-v1` while Tempo exposed an internal `POST https://unspeech-production.up.railway.app/v1/audio/speech` span returning upstream HTTP 400. Product events recorded `speech_failed` with final `http_status: 502` and reason `BAD_GATEWAY`, but Loki did not contain structured fields such as upstream HTTP status, upstream provider, upstream error code, response body snippet, or request input snippet. + +The result is an operational dead end: we can identify that one user repeatedly triggered the failure, but we cannot answer why DashScope returned 400 without replaying, guessing, or obtaining upstream-side logs. This plan turns each generation request into a correlated diagnostic record that survives across logs, traces, product events, and request logs. + +--- + +## Requirements + +**Correlation** + +- R1. Every chat, HTTP TTS, and TTS WebSocket request must carry a stable `requestId` through route logs, spans, product events, request logs, router attempts, adapter failures, billing, and final response handling. +- R2. Operators must be able to start from any one of `requestId`, `trace_id`, `userId`, product event row, or request log row and reconstruct the generation flow. +- R3. Diagnostic records must include route-level context: user id, session id when available, source, trigger, feature, action, final HTTP status, model, voice for TTS, input character count, request duration, and billing outcome. + +**Upstream Failure Detail** + +- R4. Router and adapter failures must preserve structured upstream diagnostics: upstream service, provider host, upstream URL or route name, upstream HTTP status, upstream error code, upstream error message, bounded upstream response body snippet, key id, upstream index, attempt count, and fallback decision. +- R5. The specific non-fallback TTS 400 case must be logged before the router breaks out of the fallback loop; a raw upstream 400 must not disappear just because it is not in `fallbackHttpCodes`. +- R6. AIRI may continue mapping upstream 4xx/5xx failures to client-safe 502/503 responses, but server-side diagnostics must retain the original upstream status and response details. + +**Input Diagnostics** + +- R7. Failure diagnostics must include a bounded request input snippet or payload summary for chat, HTTP TTS, and TTS WebSocket text input. +- R8. Raw input snippets and upstream response snippets must not become Prometheus labels. They belong in structured logs, trace attributes/events, product event metadata, or request-log diagnostics where cardinality and payload size are controlled. +- R9. Diagnostic snippets must be bounded by code-level defaults and environment-configurable caps to prevent large auto-TTS loops from creating unbounded log volume. + +**Storage And Metrics** + +- R10. `llm_request_log` must become drilldown-capable by storing request id, operation/source, provider, reason, input length, upstream status, and structured diagnostics for failures. +- R11. `product_events` metadata must receive scalar drilldown fields for failure diagnosis while respecting the current primitive metadata type. +- R12. Metrics must stay low-cardinality: no user ids, request ids, raw input, error messages, or response body snippets in Prometheus labels. +- R13. Observability docs must name the destination rules for logs, traces, product events, request logs, and metrics so future instrumentation does not drift again. + +--- + +## Key Technical Decisions + +- **Create one diagnostic envelope module.** A shared module should normalize route context, input summaries, upstream attempts, final status, and destination-specific projections. This prevents chat, HTTP TTS, and TTS WebSocket from each inventing field names. +- **Keep final response safety separate from server diagnostics.** `mapUpstreamError` can still return client-safe 502/503 errors, while `ApiError.cause`, structured logs, spans, product events, and request logs keep the upstream 400/429/500 details. +- **Use bounded snippets, not unbounded prompt dumps.** Default caps should be explicit, such as 512 characters for request input snippets and 2048 bytes for upstream body snippets, with env overrides. This is primarily a log-volume and storage-control boundary. +- **Store full attempts where JSON is natural, flatten where query speed matters.** Structured logs and request-log diagnostics can carry an attempts array. Product event metadata should store scalar fields such as `upstream_attempt_count`, `upstream_http_status`, `upstream_error_code`, and `input_snippet` because `ProductEventMetadata` currently allows only primitive values. +- **Route lifecycle logs are first-class, not only global error fallback.** `app.ts` global `onError` remains a safety net, but each route should emit request started, blocked, upstream failed, billing failed, succeeded, and failed events with the same diagnostic envelope. +- **Prometheus remains aggregate-only.** Counters and histograms should use low-cardinality labels such as operation, provider, model, final status, upstream status class, and fallback decision. User-level drilldown belongs in Postgres, Loki, and Tempo. +- **Fix misleading fallback accounting while adding diagnostics.** The current TTS router increments `fallbackCount` before knowing whether a status will actually fallback. The implementation should either move the increment behind the fallback decision or add a distinct attempt-failure counter so dashboards do not call non-fallback 400s "fallbacks". + +--- + +## High-Level Technical Design + +```mermaid +flowchart TB + REQ[Route receives generation request] --> CTX[Create DiagnosticContext] + CTX --> START[Log and product event: requested] + CTX --> ROUTER[LLM/TTS router] + ROUTER --> ADAPTER[Provider adapter] + ADAPTER --> UPSTREAM[UnSpeech / DashScope / other upstream] + UPSTREAM -->|non-2xx / error| ATTEMPT[Build UpstreamDiagnostic] + ATTEMPT --> ROUTER + ROUTER -->|exhausted / non-fallback| FINAL[Build final DiagnosticEnvelope] + FINAL --> LOGS[Loki structured logs] + FINAL --> TRACE[Tempo span attrs/events] + FINAL --> PRODUCT[product_events scalar metadata] + FINAL --> REQLOG[llm_request_log diagnostics jsonb] + FINAL --> METRICS[Prometheus low-cardinality metrics] + FINAL --> CLIENT[Client-safe response] +``` + +```mermaid +sequenceDiagram + participant Route as Route handler + participant Diag as Diagnostics module + participant Router as LLM/TTS router + participant Adapter as Adapter + participant Upstream as Upstream API + participant Sinks as Logs/Trace/DB/Metrics + + Route->>Diag: newContext(requestId, userId, model, source, inputSummary) + Route->>Sinks: requested event + Route->>Router: route with DiagnosticContext + Router->>Adapter: dispatch attempt + Adapter->>Upstream: HTTP request + Upstream-->>Adapter: HTTP 400 with JSON body + Adapter-->>Router: UpstreamDiagnostic(status, code, message, bodySnippet) + Router-->>Diag: attempt failed, fallback decision + Diag->>Sinks: upstream_failed diagnostics + Router-->>Route: ApiError 502 with diagnostic cause + Route->>Sinks: failed event + request log + span attrs + Route-->>Client: sanitized 502 +``` + +--- + +## Implementation Units + +### U1. Diagnostic envelope and field conventions + +- **Goal:** Define one shared representation for correlation, input summaries, upstream attempts, billing outcomes, and destination-specific projections. +- **Requirements:** R1, R2, R3, R7, R8, R9, R12, R13 +- **Files:** + - `apps/server/src/services/domain/observability-diagnostics.ts` or `apps/server/src/services/domain/observability-diagnostics/index.ts` + - `apps/server/src/services/domain/observability-diagnostics.test.ts` + - `apps/server/src/utils/observability.ts` + - `apps/server/docs/ai-context/observability-conventions.md` +- **Approach:** Add types such as `DiagnosticContext`, `InputDiagnostic`, `UpstreamDiagnostic`, `GenerationFailureDiagnostic`, and projection helpers for logs, span attributes, product event metadata, request-log diagnostics, and metric labels. Keep destination rules in code, not scattered at call sites. +- **Patterns to follow:** `apps/server/src/utils/observability.ts` for existing `airi.*` attribute naming; `apps/server/docs/ai-context/observability-conventions.md` for low-cardinality rules. +- **Test scenarios:** + - Input snippets are truncated to the configured cap and preserve `input_chars`. + - Upstream body snippets are truncated independently from input snippets. + - Product event projection contains only primitive metadata values. + - Metric projection excludes `userId`, `requestId`, raw input, error message, and body snippet. + - Log/request-log projection retains diagnostic fields needed for incident drilldown. + +### U2. Structured upstream diagnostics in router and adapters + +- **Goal:** Preserve upstream status, parsed error code/message, body snippet, and fallback decision through router failures. +- **Requirements:** R4, R5, R6, R12 +- **Files:** + - `apps/server/src/services/adapters/tts/unspeech.ts` + - `apps/server/src/services/domain/llm-router/router.ts` + - `apps/server/src/services/domain/llm-router/error-mapping.ts` + - `apps/server/src/services/domain/llm-router/tests/router.test.ts` +- **Approach:** Replace string-only TTS adapter errors with structured diagnostic fields attached to the thrown error or returned attempt failure. Parse `UnSpeechAPIError.responseBody` as JSON when possible and extract provider error code/message. Keep raw `bodySnippet` bounded. Ensure non-fallback 400s are logged and recorded before the router breaks. Revisit `fallbackCount` so it records real fallback decisions rather than all failed attempts. +- **Patterns to follow:** Existing chat non-2xx handling in `apps/server/src/services/domain/llm-router/router.ts`, which already reads `bodySnippet`; existing `UpstreamAttempt` cause shape in `apps/server/src/services/domain/llm-router/error-mapping.ts`. +- **Test scenarios:** + - UnSpeech/DashScope 400 JSON body becomes `upstream_http_status: 400`, parsed `upstream_error_code`, parsed `upstream_error_message`, and bounded `upstream_body_snippet`. + - TTS 400 that is not in `fallbackHttpCodes` still emits an upstream failure log and attaches the attempt to `ApiError.cause`. + - TTS 429 still records fallback decision and remains distinguishable from non-fallback 400. + - Chat upstream non-2xx continues preserving `bodySnippet` and now projects the same diagnostic field names. + - Metrics do not receive high-cardinality diagnostic payloads. + +### U3. Unified lifecycle diagnostics for OpenAI chat and HTTP TTS + +- **Goal:** Make non-streaming chat and HTTP TTS emit the same request lifecycle shape across logs, spans, product events, request logs, and metrics. +- **Requirements:** R1, R2, R3, R6, R7, R10, R11 +- **Files:** + - `apps/server/src/routes/openai/v1/middlewares/telemetry.ts` + - `apps/server/src/routes/openai/v1/operations/chat-completions/index.ts` + - `apps/server/src/routes/openai/v1/operations/speech-generation/index.ts` + - `apps/server/src/services/domain/openai-speech/index.ts` + - `apps/server/src/routes/openai/v1/route.test.ts` +- **Approach:** Extend `createRouteTelemetry` so both chat and speech can create a `DiagnosticContext`, record lifecycle events, and write failure request logs. Move duplicated TTS analytics fields into the shared helper where practical. Preserve existing success accounting and billing semantics. +- **Patterns to follow:** Current `createRouteTelemetry` in `apps/server/src/routes/openai/v1/middlewares/telemetry.ts`; current TTS product event sequence in `apps/server/src/services/domain/openai-speech/index.ts`. +- **Test scenarios:** + - HTTP TTS upstream 400 produces `speech_failed` metadata with request id, input chars, input snippet, upstream provider, upstream status, error code/message, body snippet, final status 502, and duration. + - Chat router exhaustion produces `completion_failed` metadata with request id, model, input summary, upstream status/body snippet, final status, and duration. + - Billing block/failure logs request id and does not pretend an upstream call happened. + - Successful chat and TTS requests keep existing request-log and product-event behavior while adding request id/source/provider fields. + - Client responses remain sanitized and do not include upstream body snippets. + +### U4. Streaming TTS WebSocket diagnostics + +- **Goal:** Bring `routes/audio-speech-ws` to the same diagnostic standard as HTTP TTS. +- **Requirements:** R1, R2, R3, R7, R10, R11 +- **Files:** + - `apps/server/src/routes/audio-speech-ws/session.ts` + - `apps/server/src/routes/audio-speech-ws/types.ts` + - `apps/server/src/routes/audio-speech-ws/route.test.ts` +- **Approach:** Thread `requestId` into start, upstream dial, upstream control event, upstream error, billing failure, close, success, product event, and request-log paths. Accumulate a bounded input snippet from text frames and record input character counts. Map upstream control errors into the shared diagnostic envelope. +- **Patterns to follow:** Existing WebSocket product event writes in `apps/server/src/routes/audio-speech-ws/session.ts`; existing request-log success write near the end of the session lifecycle. +- **Test scenarios:** + - Upstream WebSocket error records request id, user id, model, voice, input chars, input snippet, upstream code/message, and final close status. + - Upstream control error produces `speech_failed` product metadata with diagnostic fields. + - Billing failure includes request id, units, reason, and source. + - Success path writes request log with request id and operation/source. + - Input snippet cap is respected for long streaming text. + +### U5. Drilldown-capable request logs and product event metadata + +- **Goal:** Store enough persistent diagnostic data to query incidents after volatile logs age out. +- **Requirements:** R2, R3, R10, R11 +- **Files:** + - `apps/server/src/schemas/llm-request-log.ts` + - `apps/server/src/services/domain/request-log.ts` + - `apps/server/drizzle/0016_*.sql` + - `apps/server/drizzle/meta/_journal.json` + - `apps/server/drizzle/meta/0016_snapshot.json` + - `apps/server/src/schemas/product-events.ts` + - `apps/server/src/routes/openai/v1/route.test.ts` + - `apps/server/src/routes/audio-speech-ws/route.test.ts` +- **Approach:** Add request-log columns such as `request_id`, `operation`, `source`, `provider`, `reason`, `input_chars`, `upstream_status`, and `diagnostics` jsonb. Add indexes for `request_id`, `(user_id, created_at)`, and `(provider, upstream_status, created_at)` if query plans warrant them. Keep `product_events` schema stable unless type widening is needed; write scalar diagnostic metadata through U1 projections. +- **Patterns to follow:** Existing Drizzle table definitions in `apps/server/src/schemas/*.ts`; existing migration numbering under `apps/server/drizzle/`. +- **Test scenarios:** + - Failed HTTP TTS writes request log with request id, operation, provider, final status, upstream status, reason, input chars, and diagnostics jsonb. + - Failed chat writes equivalent request-log fields. + - Successful requests still write existing flux/token fields. + - Product event metadata remains primitive and query-friendly. + - Migration applies cleanly to an existing table without requiring historical rows to have request ids. + +### U6. Metrics and documentation update + +- **Goal:** Make dashboards and future instrumentation use the new diagnostic contract correctly. +- **Requirements:** R8, R12, R13 +- **Files:** + - `apps/server/src/otel/index.ts` + - `apps/server/src/utils/observability.ts` + - `apps/server/docs/ai-context/observability-conventions.md` + - `apps/server/docs/ai-context/observability-metrics.md` + - `apps/server/src/services/domain/llm-router/tests/router.test.ts` +- **Approach:** Add or revise counters for upstream attempt failures, real fallback decisions, and final route failures using low-cardinality labels. Document Loki, Tempo, Postgres, and Prometheus query patterns for request-level drilldown. Update metric docs to explain why user ids and snippets are excluded from Prometheus. +- **Patterns to follow:** Current `GatewayMetrics` in `apps/server/src/otel/index.ts`; existing metric naming conventions in `apps/server/src/utils/observability.ts`. +- **Test scenarios:** + - Upstream attempt failure increments an attempt-failure counter with provider/model/status-class labels. + - Real fallback increments fallback counter only when the router actually proceeds to another key/upstream. + - Non-fallback 400 does not appear as a fallback. + - Metric attribute helpers reject or omit high-cardinality fields. + +### U7. Incident runbook acceptance queries + +- **Goal:** Make the next incident answerable from Grafana/Loki/Tempo/Postgres without code spelunking. +- **Requirements:** R2, R13 +- **Files:** + - `apps/server/docs/ai-context/observability-runbook.md` + - `apps/server/docs/ai-context/observability-conventions.md` +- **Approach:** Document concrete query shapes: from user id to recent failed requests, from request id to Loki logs, from trace id to upstream span, from product event to request log, and from provider/status to aggregate Prometheus trends. Include the TTS 400-to-502 incident as the worked example. +- **Patterns to follow:** Existing server docs under `apps/server/docs/ai-context/`. +- **Test scenarios:** Documentation-only unit; verify manually during implementation by running the queries against a staging or production time window after deployment. + +--- + +## Acceptance Examples + +- AE1. Given DashScope returns a JSON 400 through UnSpeech during HTTP TTS, when AIRI returns client-safe 502, then Loki, Tempo, `product_events`, and `llm_request_log` expose request id, user id, source, trigger, model, voice, input chars, input snippet, upstream provider, upstream HTTP 400, parsed upstream code/message, body snippet, final 502, and duration. +- AE2. Given a chat completion upstream returns non-2xx with a response body, when the router exhausts, then `completion_failed` and request logs preserve upstream diagnostics while the client response stays sanitized. +- AE3. Given TTS WebSocket text frames are sent and the upstream control channel reports an error, then the session logs and product event include request id, input snippet, upstream code/message, close status, and billing outcome. +- AE4. Given a billing block happens before any upstream call, then diagnostics show billing reason and final status but do not fabricate upstream fields. +- AE5. Given an operator starts with a high-frequency `userId`, then they can query product events/request logs for request ids, jump to Loki by request id, and jump to Tempo by trace id without relying on raw application memory. + +--- + +## Scope Boundaries + +- In scope: server-side logs, traces, metrics, product events, request logs, router/adapters, HTTP chat, HTTP TTS, TTS WebSocket, and documentation/runbook. +- In scope: bounded failure-time input snippets and bounded upstream body snippets. +- Out of scope: front-end product analytics UI, admin dashboards, replay tooling, long-term data retention policy, and full prompt capture for every successful request. +- Out of scope: changing the client-facing error response contract except where tests need to confirm diagnostics remain server-side. + +--- + +## System-Wide Impact + +This change touches the generation hot path, observability conventions, Postgres schema, and dashboard semantics. It also changes the meaning or interpretation of fallback metrics if `fallbackCount` is corrected. The implementation should update metric docs in the same unit as metric behavior to avoid confusing existing dashboards. + +The request-log migration must be backward compatible with existing rows. New columns should be nullable unless there is a safe default. Indexes should be chosen for incident queries, not for every possible metadata field. + +--- + +## Risks & Dependencies + +- **Log volume:** Auto-TTS loops can generate hundreds of failures in minutes. Caps, failure-only snippets, and destination projections are required. +- **Metric cardinality:** Accidentally placing user ids, request ids, snippets, or raw upstream messages in labels would harm Prometheus. U1 and U6 tests should catch this. +- **Security material:** Do not log API keys, Authorization headers, encrypted key ciphertext, or full request headers. This remains a security boundary even when request text snippets are allowed. +- **Schema churn:** `llm_request_log` changes require Drizzle migration files and test updates across HTTP and WebSocket routes. +- **Partial instrumentation drift:** Implementing only TTS would leave chat and WebSocket incidents with the same blind spots. U3 and U4 should land before the plan is considered complete. + +--- + +## Sources / Research + +- `apps/server/src/app.ts` currently has global `onError` logging, but route-level upstream diagnostics are not guaranteed. +- `apps/server/src/services/domain/openai-speech/index.ts` already emits TTS request logs and product events, but failure metadata only carries final status/duration/trigger. +- `apps/server/src/routes/openai/v1/operations/chat-completions/index.ts` emits chat lifecycle product events, but router failures do not expose upstream diagnostics in product metadata. +- `apps/server/src/routes/audio-speech-ws/session.ts` has WebSocket product events and request logs, but upstream errors do not consistently include request id or input diagnostics. +- `apps/server/src/services/domain/llm-router/router.ts` already captures chat upstream `bodySnippet`; the TTS path mostly collapses adapter errors into strings and can skip logging non-fallback 400s. +- `apps/server/src/services/adapters/tts/unspeech.ts` sees `UnSpeechAPIError.responseBody`, but does not expose parsed upstream code/message as structured fields. +- `apps/server/src/services/domain/llm-router/error-mapping.ts` keeps upstream attempts server-side in `ApiError.cause`, which is the right place to preserve detail while sanitizing client responses. +- `apps/server/src/schemas/product-events.ts` stores product event metadata as primitive jsonb values and already has indexes for feature/action/time and user/time queries. +- `apps/server/src/schemas/llm-request-log.ts` is currently too thin for incident drilldown: no request id, operation/source, provider, reason, upstream status, or diagnostics jsonb. +- `apps/server/src/utils/observability.ts`, `apps/server/src/otel/index.ts`, and `apps/server/docs/ai-context/observability-conventions.md` define the existing OTel and metric conventions this plan should extend. diff --git a/packages/audio/src/audio-context/index.ts b/packages/audio/src/audio-context/index.ts index 44f1d90f9..e54088d48 100644 --- a/packages/audio/src/audio-context/index.ts +++ b/packages/audio/src/audio-context/index.ts @@ -4,6 +4,8 @@ import LibsamplerateWorkletURL from '@alexanderolsen/libsamplerate-js/dist/libsa import ProcessorWorkletURL from './processor.worklet?worker&url' +import { errorMessageFromValue } from '../utils/error-message' + let context: AudioContext | undefined let sampleRate: number = 48000 // High quality base sample rate let isReady: boolean = false @@ -128,7 +130,7 @@ export async function initializeAudioContext(requestedSampleRate: number = 48000 return context } catch (err) { - error = err instanceof Error ? err.message : String(err) + error = errorMessageFromValue(err) isReady = false workletLoaded = false notifyListeners() diff --git a/packages/audio/src/audio-context/processor.worklet.ts b/packages/audio/src/audio-context/processor.worklet.ts index 3442b3a40..c7645bbbb 100644 --- a/packages/audio/src/audio-context/processor.worklet.ts +++ b/packages/audio/src/audio-context/processor.worklet.ts @@ -4,6 +4,8 @@ import type { ConverterTypeValue } from '@alexanderolsen/libsamplerate-js/dist/c import { ConverterType, create } from '@alexanderolsen/libsamplerate-js' +import { errorMessageFromValue } from '../utils/error-message' + interface ProcessorOptions { inputSampleRate: number outputSampleRate: number @@ -68,7 +70,7 @@ class ResamplingAudioWorkletProcessor extends AudioWorkletProcessor { this.port.postMessage({ type: 'initialized', success: false, - error: error instanceof Error ? error.message : String(error), + error: errorMessageFromValue(error), }) } } @@ -142,7 +144,7 @@ class ResamplingAudioWorkletProcessor extends AudioWorkletProcessor { this.port.postMessage({ type: 'error', - error: error instanceof Error ? error.message : String(error), + error: errorMessageFromValue(error), }) // Pass through original data on error diff --git a/packages/audio/src/utils/error-message.ts b/packages/audio/src/utils/error-message.ts new file mode 100644 index 000000000..b44d805e0 --- /dev/null +++ b/packages/audio/src/utils/error-message.ts @@ -0,0 +1,17 @@ +import { errorMessageFrom } from '@moeru/std' + +/** + * Returns an error message while preserving JavaScript string fallback. + * + * Use when: + * - Audio runtime diagnostics need the previous `String(error)` fallback. + * + * Expects: + * - `error` may be any thrown value. + * + * Returns: + * - The extracted error message, else `String(error)`. + */ +export function errorMessageFromValue(error: unknown): string { + return errorMessageFrom(error) ?? String(error) +} diff --git a/packages/cap-vite/package.json b/packages/cap-vite/package.json index 66398b535..c55788334 100644 --- a/packages/cap-vite/package.json +++ b/packages/cap-vite/package.json @@ -40,6 +40,7 @@ "vite": "^7.0.0 || ^8.0.0-beta.0" }, "dependencies": { + "@moeru/std": "catalog:", "cac": "catalog:", "tinyexec": "catalog:" } diff --git a/packages/cap-vite/src/bin/run.ts b/packages/cap-vite/src/bin/run.ts index a870fa7c1..f9f2eed5a 100644 --- a/packages/cap-vite/src/bin/run.ts +++ b/packages/cap-vite/src/bin/run.ts @@ -4,6 +4,7 @@ import process from 'node:process' import { runCapVite } from '..' import { getCapViteCliHelpText, parseCapViteCliArgs } from '../cli' +import { errorMessageFromValue } from '../utils/error-message' async function main() { const parsed = parseCapViteCliArgs(process.argv.slice(2)) @@ -19,6 +20,6 @@ async function main() { } void main().catch((error) => { - process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`) + process.stderr.write(`${errorMessageFromValue(error)}\n`) process.exit(1) }) diff --git a/packages/cap-vite/src/utils/error-message.ts b/packages/cap-vite/src/utils/error-message.ts new file mode 100644 index 000000000..12d1e5986 --- /dev/null +++ b/packages/cap-vite/src/utils/error-message.ts @@ -0,0 +1,17 @@ +import { errorMessageFrom } from '@moeru/std' + +/** + * Returns an error message while preserving JavaScript string fallback. + * + * Use when: + * - CLI and Vite plugin diagnostics need a message for arbitrary thrown values. + * + * Expects: + * - `error` may be any thrown value. + * + * Returns: + * - The extracted error message, else `String(error)`. + */ +export function errorMessageFromValue(error: unknown): string { + return errorMessageFrom(error) ?? String(error) +} diff --git a/packages/cap-vite/src/vite-plugin.ts b/packages/cap-vite/src/vite-plugin.ts index fad382e50..53329afeb 100644 --- a/packages/cap-vite/src/vite-plugin.ts +++ b/packages/cap-vite/src/vite-plugin.ts @@ -12,6 +12,7 @@ import * as readline from 'node:readline' import { x } from 'tinyexec' import { parseCapacitorPlatform, pickServerUrl, resolveCapRunArgs, shouldRestartForNativeChange } from './native' +import { errorMessageFromValue } from './utils/error-message' export interface CapVitePluginOptions { capArgs: string[] @@ -166,7 +167,7 @@ export function capVitePlugin(options: CapVitePluginOptions): Plugin { } } catch (error) { - logger.error(`[cap-vite] ${error instanceof Error ? error.message : String(error)}`) + logger.error(`[cap-vite] ${errorMessageFromValue(error)}`) await shutdown() } finally { diff --git a/packages/core-agent/src/runtime/llm-service.ts b/packages/core-agent/src/runtime/llm-service.ts index 8ce0d82f0..23d47e1ed 100644 --- a/packages/core-agent/src/runtime/llm-service.ts +++ b/packages/core-agent/src/runtime/llm-service.ts @@ -3,10 +3,11 @@ import type { Message, Tool } from '@xsai/shared-chat' import type { StreamFromOptions, StreamOptions } from '../types/llm' -import { errorMessageFrom } from '@moeru/std' import { stepCountAtLeast } from '@xsai/shared-chat' import { streamText } from '@xsai/stream-text' +import { errorMessageFromValue } from '../utils/error-message' + /** * Normalize chat messages so they match the wire format the active provider * actually accepts, flattening content-part arrays back to plain strings when @@ -109,7 +110,7 @@ function isAbortError(error: unknown): boolean { } function createCapturedToolErrorResult(toolName: string, error: unknown): string { - return `Tool call error for "${toolName}": ${errorMessageFrom(error) ?? String(error)}` + return `Tool call error for "${toolName}": ${errorMessageFromValue(error)}` } function withCapturedToolErrors( diff --git a/packages/core-agent/src/utils/error-message.ts b/packages/core-agent/src/utils/error-message.ts new file mode 100644 index 000000000..c9cbfdfef --- /dev/null +++ b/packages/core-agent/src/utils/error-message.ts @@ -0,0 +1,17 @@ +import { errorMessageFrom } from '@moeru/std' + +/** + * Returns an error message while preserving JavaScript string fallback. + * + * Use when: + * - Agent runtime diagnostics need a message for arbitrary thrown values. + * + * Expects: + * - `error` may be any thrown value. + * + * Returns: + * - The extracted error message, else `String(error)`. + */ +export function errorMessageFromValue(error: unknown): string { + return errorMessageFrom(error) ?? String(error) +} diff --git a/packages/i18n/src/locales/ja/settings.yaml b/packages/i18n/src/locales/ja/settings.yaml index 67e993932..adac07883 100644 --- a/packages/i18n/src/locales/ja/settings.yaml +++ b/packages/i18n/src/locales/ja/settings.yaml @@ -64,8 +64,8 @@ dialogs: stateGranted: 許可済み stateNotGranted: 許可されていません bug-report: - title: バク報告 (´;ω;`)ヾ(・∀・`) - subtitle: "予期せぬエラーが発生しました \n何が起こったか報告してくれませんか?" + title: バク報告 (´;ω;`)ヾ(・∀・`) + subtitle: "予期せぬエラーが発生しました\n何が起こったか報告してくれませんか?" trigger-label: バグを報告 submit-label: バグ報告を送信 triage-description: この問題の解決のためにページ内容とスクリーンショットを含める。 diff --git a/packages/model-driver-mediapipe/tasks/error-message.ts b/packages/model-driver-mediapipe/tasks/error-message.ts new file mode 100644 index 000000000..b320e2fea --- /dev/null +++ b/packages/model-driver-mediapipe/tasks/error-message.ts @@ -0,0 +1,17 @@ +import { errorMessageFrom } from '@moeru/std' + +/** + * Returns an error message while preserving JavaScript string fallback. + * + * Use when: + * - Task scripts need a message for arbitrary thrown values. + * + * Expects: + * - `error` may be any thrown value. + * + * Returns: + * - The extracted error message, else `String(error)`. + */ +export function errorMessageFromValue(error: unknown): string { + return errorMessageFrom(error) ?? String(error) +} diff --git a/packages/model-driver-mediapipe/tasks/prepare-tasks.ts b/packages/model-driver-mediapipe/tasks/prepare-tasks.ts index 7416fb1f2..718596d92 100644 --- a/packages/model-driver-mediapipe/tasks/prepare-tasks.ts +++ b/packages/model-driver-mediapipe/tasks/prepare-tasks.ts @@ -12,6 +12,7 @@ import { withRetry } from '@moeru/std' import { attemptAsync } from 'es-toolkit' import { ofetch } from 'ofetch' +import { errorMessageFromValue } from './error-message' import { visionTaskAssets } from './tasks' const taskSources: Record = { @@ -62,7 +63,7 @@ async function downloadAsset(key: string, url: string, outputPath: string) { } }, { onError: (error) => { - const message = error instanceof Error ? error.message : String(error) + const message = errorMessageFromValue(error) console.warn(`Failed to download MediaPipe vision task asset for ${key} (attempt ${attempt}): ${message}`) }, }) diff --git a/packages/pipelines-audio/src/managers/playback-manager.ts b/packages/pipelines-audio/src/managers/playback-manager.ts index 7c9506c46..b9532cab0 100644 --- a/packages/pipelines-audio/src/managers/playback-manager.ts +++ b/packages/pipelines-audio/src/managers/playback-manager.ts @@ -6,6 +6,8 @@ import type { PlaybackStartEvent, } from '../types' +import { errorMessageFrom } from '@moeru/std' + export type OverflowPolicy = 'queue' | 'reject' | 'steal-oldest' | 'steal-lowest-priority' export type OwnerOverflowPolicy = 'reject' | 'steal-oldest' @@ -141,7 +143,7 @@ export function createPlaybackManager(options: PlaybackManagerOptions { avatarLoadError.value = false }) +watch(userAvatar, () => { + avatarLoadError.value = false +}) const formattedCredits = computed(() => credits.value.toLocaleString()) diff --git a/packages/stage-pages/src/pages/devtools/plugin-host.vue b/packages/stage-pages/src/pages/devtools/plugin-host.vue index ac5f00d0c..9aabf130e 100644 --- a/packages/stage-pages/src/pages/devtools/plugin-host.vue +++ b/packages/stage-pages/src/pages/devtools/plugin-host.vue @@ -4,6 +4,7 @@ import type { PluginManifestSummary, } from '@proj-airi/stage-ui/stores/devtools/plugin-host-debug' +import { errorMessageFrom } from '@moeru/std' import { Section } from '@proj-airi/stage-ui/components' import { usePluginHostInspectorStore } from '@proj-airi/stage-ui/stores/devtools/plugin-host-debug' import { Button, Callout, Input } from '@proj-airi/ui' @@ -93,7 +94,7 @@ async function refresh() { await store.refreshAll() } catch (error) { - toast.error(error instanceof Error ? error.message : 'Failed to refresh plugin host debug state.') + toast.error(errorMessageFrom(error) ?? 'Failed to refresh plugin host debug state.') } } @@ -102,7 +103,7 @@ async function loadEnabled() { await store.loadEnabled() } catch (error) { - toast.error(error instanceof Error ? error.message : 'Failed to load enabled plugins.') + toast.error(errorMessageFrom(error) ?? 'Failed to load enabled plugins.') } } @@ -114,7 +115,7 @@ async function setAutoReload(plugin: PluginManifestSummary, enabled: boolean) { }) } catch (error) { - toast.error(error instanceof Error ? error.message : `Failed to update auto-reload state for ${plugin.name}.`) + toast.error(errorMessageFrom(error) ?? `Failed to update auto-reload state for ${plugin.name}.`) } } @@ -127,7 +128,7 @@ async function setEnabled(plugin: PluginManifestSummary, enabled: boolean) { }) } catch (error) { - toast.error(error instanceof Error ? error.message : `Failed to update enabled state for ${plugin.name}.`) + toast.error(errorMessageFrom(error) ?? `Failed to update enabled state for ${plugin.name}.`) } } @@ -136,7 +137,7 @@ async function loadPlugin(plugin: PluginManifestSummary) { await store.load({ name: plugin.name }) } catch (error) { - toast.error(error instanceof Error ? error.message : `Failed to load plugin ${plugin.name}.`) + toast.error(errorMessageFrom(error) ?? `Failed to load plugin ${plugin.name}.`) } } @@ -145,7 +146,7 @@ async function unloadPlugin(plugin: PluginManifestSummary) { await store.unload({ name: plugin.name }) } catch (error) { - toast.error(error instanceof Error ? error.message : `Failed to unload plugin ${plugin.name}.`) + toast.error(errorMessageFrom(error) ?? `Failed to unload plugin ${plugin.name}.`) } } @@ -160,7 +161,7 @@ async function loadSelectedPlugin() { await store.load({ name }) } catch (error) { - toast.error(error instanceof Error ? error.message : `Failed to load plugin ${name}.`) + toast.error(errorMessageFrom(error) ?? `Failed to load plugin ${name}.`) } } diff --git a/packages/stage-pages/src/pages/devtools/providers-transcription-realtime-aliyun-nls.vue b/packages/stage-pages/src/pages/devtools/providers-transcription-realtime-aliyun-nls.vue index 0833f5475..1dab734e5 100644 --- a/packages/stage-pages/src/pages/devtools/providers-transcription-realtime-aliyun-nls.vue +++ b/packages/stage-pages/src/pages/devtools/providers-transcription-realtime-aliyun-nls.vue @@ -3,6 +3,7 @@ import type { ServerEvent, ServerEvents } from '@proj-airi/stage-ui/stores/provi import vadWorkletUrl from '@proj-airi/stage-ui/workers/vad/process.worklet?worker&url' +import { errorMessageFromValue } from '@proj-airi/stage-shared' import { createAliyunNLSProvider, streamAliyunTranscription } from '@proj-airi/stage-ui/stores/providers/aliyun/stream-transcription' import { Button, FieldCombobox, FieldInput } from '@proj-airi/ui' import { computed, nextTick, onBeforeUnmount, reactive, ref, shallowRef, watch } from 'vue' @@ -177,7 +178,7 @@ async function startRecording() { }, onSessionTerminated: (error) => { if (error) { - appendLog(`Session terminated: ${error instanceof Error ? error.message : String(error)}`, 'error') + appendLog(`Session terminated: ${errorMessageFromValue(error)}`, 'error') isTranscribing.value = false } }, @@ -199,7 +200,7 @@ async function startRecording() { if (error instanceof DOMException && error.name === 'AbortError') appendLog('Transcription aborted by user') else - appendLog(`Transcription failed: ${error instanceof Error ? error.message : String(error)}`, 'error') + appendLog(`Transcription failed: ${errorMessageFromValue(error)}`, 'error') }) .finally(() => { isTranscribing.value = false @@ -229,7 +230,7 @@ async function startRecording() { } catch (error) { console.error(error) - appendLog(`Failed to start recording: ${error instanceof Error ? error.message : String(error)}`, 'error') + appendLog(`Failed to start recording: ${errorMessageFromValue(error)}`, 'error') audioStreamController.value?.error(error instanceof Error ? error : new Error(String(error))) audioStreamController.value = undefined abortTranscription() diff --git a/packages/stage-pages/src/pages/settings/account/account-settings-page.vue b/packages/stage-pages/src/pages/settings/account/account-settings-page.vue index f235d4d85..af02a7971 100644 --- a/packages/stage-pages/src/pages/settings/account/account-settings-page.vue +++ b/packages/stage-pages/src/pages/settings/account/account-settings-page.vue @@ -45,7 +45,9 @@ const gravatarProfileUrl = computed(() => { // instead of rendering an alt-text overflow inside the circle. Resets when // the URL changes so a fixed URL re-attempts loading. const avatarLoadError = ref(false) -watch(userAvatar, () => { avatarLoadError.value = false }) +watch(userAvatar, () => { + avatarLoadError.value = false +}) // Locale-aware thousand separator. Bare 5–6 digit numbers are noisy to scan // (e.g. "44965" reads as one block); Intl.NumberFormat respects user locale diff --git a/packages/stage-pages/src/pages/settings/airi-card/components/CardCreationDialog.vue b/packages/stage-pages/src/pages/settings/airi-card/components/CardCreationDialog.vue index 128f58ae0..fc929ab90 100644 --- a/packages/stage-pages/src/pages/settings/airi-card/components/CardCreationDialog.vue +++ b/packages/stage-pages/src/pages/settings/airi-card/components/CardCreationDialog.vue @@ -316,7 +316,7 @@ function saveCard(card: Card): boolean { throw new Error('Not an object') } } - catch (e) { + catch { showError.value = true errorMessage.value = t('settings.pages.card.creation.errors.invalid_artistry_json') return false diff --git a/packages/stage-pages/src/pages/settings/airi-card/components/CardDetailDialog.vue b/packages/stage-pages/src/pages/settings/airi-card/components/CardDetailDialog.vue index ac6f966b5..301a85dca 100644 --- a/packages/stage-pages/src/pages/settings/airi-card/components/CardDetailDialog.vue +++ b/packages/stage-pages/src/pages/settings/airi-card/components/CardDetailDialog.vue @@ -213,8 +213,19 @@ async function handleSetAsBackground(entry: any) { activeBackgroundId.value = entry.id } +function requestDeleteConfirmation(message: string): boolean { + // NOTICE: + // Native confirm is the existing guard for this destructive gallery action. + // Root cause: `no-alert` rejects direct `confirm(...)` calls before this page + // has a shared confirmation-dialog primitive wired into the card settings flow. + // Source/context: this component already used native confirm for journal delete. + // Removal condition: replace with the shared modal confirmation component. + const confirmAction = globalThis.confirm.bind(globalThis) + return confirmAction(message) +} + async function handleDeleteEntry(id: string) { - if (confirm('Are you sure you want to delete this image from the journal?')) { + if (requestDeleteConfirmation('Are you sure you want to delete this image from the journal?')) { await backgroundStore.removeBackground(id) } } diff --git a/packages/stage-pages/src/pages/settings/modules/hearing.vue b/packages/stage-pages/src/pages/settings/modules/hearing.vue index 91cef3c2b..b58ef241a 100644 --- a/packages/stage-pages/src/pages/settings/modules/hearing.vue +++ b/packages/stage-pages/src/pages/settings/modules/hearing.vue @@ -1,6 +1,7 @@ diff --git a/packages/stage-ui/src/components/scenarios/dialogs/onboarding/onboarding.vue b/packages/stage-ui/src/components/scenarios/dialogs/onboarding/onboarding.vue index d0cec2730..e5bf6d5a5 100644 --- a/packages/stage-ui/src/components/scenarios/dialogs/onboarding/onboarding.vue +++ b/packages/stage-ui/src/components/scenarios/dialogs/onboarding/onboarding.vue @@ -108,11 +108,6 @@ async function saveProviderConfiguration(data: ProviderConfigData) { } } -async function handleSave() { - capturePosthogEvent('onboarding_step_completed', { step: currentStep.value?.id ?? 'unknown' }) - emit('configured') -} - const allSteps = computed(() => { const coreSteps: OnboardingStep[] = [ { @@ -163,6 +158,11 @@ const currentStep = computed(() => allSteps.value[step.value] ?? null) const isLastStep = computed(() => step.value === allSteps.value.length - 1) const currentStepProps = computed(() => currentStep.value?.props?.() ?? {}) +async function handleSave() { + capturePosthogEvent('onboarding_step_completed', { step: currentStep.value?.id ?? 'unknown' }) + emit('configured') +} + async function canPassGuard(guard?: OnboardingStepGuard) { if (!guard) return true diff --git a/packages/stage-ui/src/components/scenarios/providers/speech-playground-openai-compatible.vue b/packages/stage-ui/src/components/scenarios/providers/speech-playground-openai-compatible.vue index 8993fd512..b2d2d9f60 100644 --- a/packages/stage-ui/src/components/scenarios/providers/speech-playground-openai-compatible.vue +++ b/packages/stage-ui/src/components/scenarios/providers/speech-playground-openai-compatible.vue @@ -1,4 +1,5 @@