@burdenoff/microfe-bigconsole 2026.730.3 → 2026.730.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/dist/bigconsole/assistant/attachmentExtract.js +50 -0
  2. package/dist/bigconsole/assistant/attachmentExtract.js.map +1 -0
  3. package/dist/bigconsole/assistant/createSandboxAssistantTransport.js +174 -173
  4. package/dist/bigconsole/assistant/createSandboxAssistantTransport.js.map +1 -1
  5. package/dist/bigconsole/components/embed/EmbedErrorBoundary.js +25 -0
  6. package/dist/bigconsole/components/embed/EmbedErrorBoundary.js.map +1 -0
  7. package/dist/bigconsole/components/embed/EmbedWidgetRenderer.js +36 -0
  8. package/dist/bigconsole/components/embed/EmbedWidgetRenderer.js.map +1 -0
  9. package/dist/bigconsole/components/embed/ReadOnlyDashboardRenderer.js +62 -0
  10. package/dist/bigconsole/components/embed/ReadOnlyDashboardRenderer.js.map +1 -0
  11. package/dist/bigconsole/components/embed/index.js +7 -0
  12. package/dist/bigconsole/components/embed/renderer-manifest.js +77 -0
  13. package/dist/bigconsole/components/embed/renderer-manifest.js.map +1 -0
  14. package/dist/bigconsole/components/embed/types.js +6 -0
  15. package/dist/bigconsole/components/embed/types.js.map +1 -0
  16. package/dist/bigconsole/components/embed/validate.js +29 -0
  17. package/dist/bigconsole/components/embed/validate.js.map +1 -0
  18. package/dist/bigconsole/components/embed/widgets/KpiComparisonEmbed.js +34 -0
  19. package/dist/bigconsole/components/embed/widgets/KpiComparisonEmbed.js.map +1 -0
  20. package/dist/bigconsole/components/embed/widgets/ListEmbed.js +36 -0
  21. package/dist/bigconsole/components/embed/widgets/ListEmbed.js.map +1 -0
  22. package/dist/bigconsole/components/embed/widgets/MetricCardEmbed.js +20 -0
  23. package/dist/bigconsole/components/embed/widgets/MetricCardEmbed.js.map +1 -0
  24. package/dist/bigconsole/components/embed/widgets/TableEmbed.js +40 -0
  25. package/dist/bigconsole/components/embed/widgets/TableEmbed.js.map +1 -0
  26. package/dist/bigconsole/components/embed/widgets/TextEmbed.js +20 -0
  27. package/dist/bigconsole/components/embed/widgets/TextEmbed.js.map +1 -0
  28. package/dist/bigconsole/components/embed/widgets/shared.js +29 -0
  29. package/dist/bigconsole/components/embed/widgets/shared.js.map +1 -0
  30. package/dist/node_modules/pdfjs-dist/build/pdf.js +12493 -0
  31. package/dist/node_modules/pdfjs-dist/build/pdf.js.map +1 -0
  32. package/dist/node_modules/xlsx/xlsx.js +16412 -0
  33. package/dist/node_modules/xlsx/xlsx.js.map +1 -0
  34. package/package.json +8 -2
@@ -1 +1 @@
1
- {"version":3,"file":"createSandboxAssistantTransport.js","names":[],"sources":["../../../src/bigconsole/assistant/createSandboxAssistantTransport.ts"],"sourcesContent":["/**\n * BigConsole adapter for the shared fe-libs AssistantWidget.\n *\n * The floating widget (fe-libs, Layer 1) is backend-agnostic — it calls an\n * injected `AssistantTransport`. This hook builds a transport that drives the\n * sandbox AI assistant (combined `assistant` mode = docs Q&A + api-calls): it\n * provisions/reuses a sandbox, opens a session, dispatches the prompt async,\n * then polls for the streamed answer. The agent introspects the GraphQL schema\n * and performs API calls on the user's behalf using their workspace token,\n * contextual to the current screen (via `gatherPageContext`).\n *\n * This is a faithful port of microfe-vibecontrols'\n * `services/createSandboxAssistantTransport.ts`; the only product-specific\n * difference lives in `assistantApi.createAssistantSandbox`\n * (`AI_ASSISTANT_PRODUCT=bigconsole`).\n */\n\nimport { useCallback, useMemo, useRef } from 'react';\nimport { useAuthToken } from '@burdenoff/fe-libs/shared/providers/shell';\nimport {\n createAssistantSandbox,\n createAssistantSession,\n extendAssistantSandboxTTL,\n findExistingSandbox,\n getAssistantMessages,\n sendAssistantPromptAsync,\n waitForAssistantServiceReady,\n waitForSandboxReady,\n} from './assistantApi';\nimport { useAssistantRunStore } from './assistantRunStore';\nimport {\n type AssistantConversationSummary,\n type AssistantHistoryTurnMessage,\n deleteAssistantConversation,\n getAssistantConversationMessages,\n listAssistantConversations,\n saveAssistantTurn,\n} from './conversationHistoryApi';\nimport { gatherPageContext } from './pageContext';\nimport type { AssistantMode, AssistantRawMessage, AssistantRawMessagePart, AssistantSandboxAuthContext } from './types';\n\n/**\n * Locally-defined mirror of the fe-libs `AssistantTransport` contract.\n *\n * Intentionally NOT imported from `@burdenoff/fe-libs`: microfe's tsconfig maps\n * `@burdenoff/fe-libs/*` to fe-libs *source*, so vite-plugin-dts would rewrite a\n * cross-package type used in this hook's public signature to a broken\n * source-relative path in the emitted `.d.ts`. Structural typing makes this\n * shape assignable to fe-libs' `AssistantTransport` at the call site\n * (bigconsole-app's AppShell), which is where compatibility is enforced.\n */\ninterface AssistantSendArgs {\n prompt: string;\n onProgress: (partialText: string) => void;\n signal: AbortSignal;\n}\n\n/** Mirror of fe-libs' `AssistantWidgetMessage` (see note above on why). */\ninterface AssistantHistoryMessage {\n id: string;\n role: 'user' | 'assistant';\n content: string;\n pending?: boolean;\n error?: boolean;\n}\n\n/** Mirror of fe-libs' `AssistantSessionSummary` (see note above on why). */\ninterface AssistantSessionSummaryLocal {\n id: string;\n title: string;\n updatedAt?: number;\n active?: boolean;\n}\n\nexport interface AssistantTransport {\n sendPrompt: (args: AssistantSendArgs) => Promise<{ text: string }>;\n loadHistory: () => Promise<AssistantHistoryMessage[]>;\n listSessions: () => Promise<AssistantSessionSummaryLocal[]>;\n newSession: () => Promise<void>;\n deleteSession: (sessionId: string) => Promise<void>;\n selectSession: (sessionId: string) => Promise<AssistantHistoryMessage[]>;\n}\n\n// BigConsole still boots the manually-tagged ACA image\n// `alpha-delegated-auth-v11` for the assistant sandbox. The historical\n// platform notes show that this image line reliably supports `api-calls`, while\n// the combined `assistant` mode depends on newer image contracts that are not\n// yet guaranteed on this tag. Use `api-calls` here so the assistant can execute\n// workspace GraphQL operations end-to-end right now. Once the underlying image\n// line is rebuilt and verified for combined mode, this can be switched back.\nconst MODE: AssistantMode = 'api-calls';\n// How long the UI will follow a single turn.\n//\n// This was 180s, which was SHORTER THAN THE WORK. A full \"create a school\n// attendance dashboard\" build — datasink → dashboard → parser → widget, each a\n// separate gateway call preceded by a model round-trip — measured 229s in prod.\n// So the agent finished, the dashboard genuinely existed, and the user was still\n// shown \"the assistant timed out\". That is worse than cosmetic: people retry and\n// end up with duplicate dashboards.\n//\n// 7 minutes covers the observed worst case with headroom. It costs nothing on\n// fast turns (we stop the moment the turn reports done), and the backend keeps\n// pace — the sandbox TTL is extended every TTL_EXTEND_INTERVAL_MS.\nconst STREAM_BUDGET_MS = 420_000;\nconst POLL_INTERVAL_MS = 1500;\nconst TTL_EXTEND_INTERVAL_MS = 30_000;\n// Raw agent messages per restore. The agent emits one message per internal\n// step, so a handful of turns is already dozens of messages — this is a cap on\n// the RAW fetch, not on the number of restored turns.\nconst HISTORY_MESSAGE_LIMIT = 200;\n/** Chats shown in History. Titles come from the store, so listing is one query. */\nconst SESSION_LIST_LIMIT = 25;\n/**\n * Cap on the transcript replayed into a resumed agent session. Long enough to\n * carry the ids and decisions that make \"that dashboard\" resolvable, short\n * enough not to crowd out the actual prompt.\n */\nconst REPLAY_MAX_CHARS = 6000;\n\nconst SANDBOX_ID_KEY = 'bc-assistant-sandbox-id';\nconst SESSION_ID_KEY = 'bc-assistant-session-id';\n/** The durable chat. This is the identity History lists. */\nconst CONVERSATION_ID_KEY = 'bc-assistant-conversation-id';\n\nfunction readStoredId(key: string): string | null {\n try {\n return window.sessionStorage.getItem(key);\n } catch {\n // sessionStorage unavailable (private mode) — degrade to a fresh session.\n return null;\n }\n}\n\nfunction writeStoredId(key: string, id: string | null): void {\n try {\n if (id) window.sessionStorage.setItem(key, id);\n else window.sessionStorage.removeItem(key);\n } catch {\n // Non-fatal: we simply lose cross-reload continuity.\n }\n}\n\n// ── Context helpers (mirror vibecontrols' resolution) ────────────────\n\nfunction getProfileContextValue(key: 'workspaceId' | 'organizationId'): string {\n try {\n const activeContextKey =\n key === 'workspaceId' ? 'burdenoff-active-context-workspace' : 'burdenoff-active-context-organization';\n const activeContextValue = localStorage.getItem(activeContextKey);\n if (activeContextValue) return activeContextValue;\n\n const activeProfileId = sessionStorage.getItem('bf-active-profile');\n if (!activeProfileId) return '';\n const raw = localStorage.getItem(`bf-p-${activeProfileId}-context`);\n if (!raw) return '';\n const context = JSON.parse(raw) as { workspaceId?: string; organizationId?: string };\n return context[key] ?? '';\n } catch {\n return '';\n }\n}\n\nfunction getWorkspaceId(fallback: string | null): string {\n const params = new URLSearchParams(window.location.search);\n return params.get('workspace') ?? getProfileContextValue('workspaceId') ?? fallback ?? '';\n}\n\nfunction getOrganizationId(): string {\n const params = new URLSearchParams(window.location.search);\n return params.get('org') ?? getProfileContextValue('organizationId');\n}\n\n// ── Message-progress helpers (pure; mirror vibecontrols) ─────────────\n\nfunction getMessageRole(message: AssistantRawMessage): string | undefined {\n // Check nested format first, then flat format\n return message.info?.role ?? message.role;\n}\n\nfunction getRawMessageCreatedAt(message: AssistantRawMessage): number {\n // Check nested format first (epoch ms), then flat format (ISO string or epoch ms)\n const nested = message.info?.time?.created;\n if (nested !== undefined) return nested;\n const flat = message.createdAt;\n if (flat === undefined) return 0;\n // If it's a string (ISO), parse it; otherwise treat as epoch ms\n if (typeof flat === 'string') {\n const parsed = Date.parse(flat);\n return isNaN(parsed) ? 0 : parsed;\n }\n return flat;\n}\n\nfunction getMessageCompleted(message: AssistantRawMessage): number | undefined {\n // Check nested format first, then flat format\n const nested = message.info?.time?.completed;\n if (nested !== undefined) return nested;\n const flat = message.completedAt;\n if (flat === undefined) return undefined;\n if (typeof flat === 'string') {\n const parsed = Date.parse(flat);\n return isNaN(parsed) ? undefined : parsed;\n }\n return flat;\n}\n\nfunction getAssistantText(message: AssistantRawMessage): string {\n // Check parts format first (nested), then flat content\n const parts = message.parts ?? [];\n const textFromParts = (parts ?? [])\n .filter((part) => part.type === 'text' && typeof part.text === 'string')\n .map((part) => part.text?.trim() ?? '')\n .filter(Boolean)\n .join('\\n');\n if (textFromParts) return textFromParts;\n // Fallback to flat content field\n return typeof message.content === 'string' ? message.content.trim() : '';\n}\n\n// Friendly, human-readable labels for the agent's tools so the progress line\n// reads like \"Searching the schema…\" instead of \"Running: bash\". The agent sets\n// a `description` on every bash call (e.g. \"Search for sales-related types in\n// workspace schema\") and a todo list on todowrite — surface those directly.\nconst TOOL_LABELS: Record<string, string> = {\n bash: 'Running a command',\n webfetch: 'Fetching a page',\n 'file.read': 'Reading files',\n 'file.write': 'Writing files',\n 'file.edit': 'Editing files',\n 'file.find.text': 'Searching the code',\n 'file.find.file': 'Looking for files',\n todowrite: 'Planning the steps',\n todoread: 'Reviewing the plan',\n};\n\nfunction asRecord(value: unknown): Record<string, unknown> | undefined {\n return typeof value === 'object' && value !== null ? (value as Record<string, unknown>) : undefined;\n}\n\n/** Best-effort human summary of what a single tool part is doing right now. */\nfunction describeToolPart(part: AssistantRawMessagePart): string {\n const tool = part.tool ?? 'tool';\n const input = asRecord(part.state?.input);\n\n // bash carries a plain-English `description` of the step — the best signal.\n const description = input?.description;\n if (typeof description === 'string' && description.trim()) return description.trim();\n\n // todowrite carries the todo list — surface the item being worked on.\n const todos = input?.todos;\n if (Array.isArray(todos)) {\n const active = todos.find((todo) => asRecord(todo)?.status === 'in_progress') ?? todos[0];\n const content = asRecord(active)?.content;\n if (typeof content === 'string' && content.trim()) return content.trim();\n }\n\n return TOOL_LABELS[tool] ?? `Running ${tool}`;\n}\n\nfunction getToolProgress(message: AssistantRawMessage): string[] {\n const parts = message.parts ?? [];\n return parts\n .filter((part) => part.type === 'tool' && part.tool)\n .map((part) => {\n const status = part.state?.status ?? 'running';\n const label = describeToolPart(part);\n if (status === 'completed') return `✓ ${label}`;\n if (status === 'failed') return `⚠ ${label}`;\n return `⏳ ${label}…`;\n });\n}\n\nfunction buildProgress(\n messages: AssistantRawMessage[],\n sinceMs: number,\n previousContent?: string,\n previousContentAtMs?: number\n): { content: string; done: boolean } {\n const relevant = messages\n .filter((message) => getMessageRole(message) === 'assistant' && getRawMessageCreatedAt(message) >= sinceMs)\n .sort((left, right) => getRawMessageCreatedAt(left) - getRawMessageCreatedAt(right));\n\n // Debug: log message filtering when no relevant messages found\n if (relevant.length === 0 && messages.length > 0) {\n console.log('[BigConsole-Assistant] buildProgress: no relevant messages', {\n totalMessages: messages.length,\n sinceMs,\n messageRoles: messages.map((m) => getMessageRole(m)),\n messageTimestamps: messages.map((m) => getRawMessageCreatedAt(m)),\n });\n }\n\n let content: string;\n let done: boolean;\n\n if (relevant.length === 0) {\n content = '';\n // Staleness fallback: if no messages have appeared after 15+ seconds of polling,\n // treat the response as complete even when messages get filtered out\n // (e.g., due to timestamp skew or role mismatch).\n done =\n previousContent === content && previousContentAtMs !== undefined && Date.now() - previousContentAtMs >= 15_000;\n } else {\n const latest = relevant[relevant.length - 1]!;\n\n // ACCUMULATE the run, don't just show its last line.\n //\n // The agent emits a message per step, and it now narrates each one and prints\n // a link the moment a create lands (\"✅ Data sink created — [Open …](/…)\").\n // Showing only the newest message threw all of that away a second later: the\n // user saw a lone \"Thinking…\" and none of the links they were promised. Join\n // the whole run instead, so the panel reads as a live account of what is\n // happening and every link stays on screen.\n const narration = relevant.map(getAssistantText).filter(Boolean);\n const toolProgress = getToolProgress(latest);\n content = [...narration, ...toolProgress].join('\\n\\n');\n\n const officiallyDone = Boolean(getMessageCompleted(latest)) && content.length > 0;\n\n // A tool that is still running is proof the turn is alive, so never let the\n // staleness fallback fire underneath it. A single gateway call can sit on the\n // same \"⏳ Creating the data sink…\" line for far longer than the old 15s\n // window, which would have declared the turn finished mid-build.\n const hasRunningTool = (latest.parts ?? []).some(\n (part) => part.type === 'tool' && part.state?.status !== 'completed' && part.state?.status !== 'failed'\n );\n\n const staleDone =\n !officiallyDone &&\n !hasRunningTool &&\n previousContent === content &&\n previousContentAtMs !== undefined &&\n Date.now() - previousContentAtMs >= 45_000;\n\n done = officiallyDone || staleDone;\n }\n\n return { content, done };\n}\n\nfunction sanitize(response: string): string {\n return response\n .replace(/(Authorization\\s*:\\s*Bearer\\s+)[^\\s\\n]+/gi, '$1[REDACTED]')\n .replace(/(X-Workspace-Authorization\\s*:\\s*Bearer\\s+)[^\\s\\n]+/gi, '$1[REDACTED]')\n .replace(/\\beyJ[A-Za-z0-9_-]+\\.[A-Za-z0-9._-]+\\.[A-Za-z0-9._-]+\\b/g, '[REDACTED_JWT]')\n .replace(/\\bsk-ant-[A-Za-z0-9-]+\\b/g, '[REDACTED_API_KEY]');\n}\n\nfunction isRecoverable(error: unknown): boolean {\n const message = error instanceof Error ? error.message.toLowerCase() : String(error).toLowerCase();\n if (\n message.includes('rate limit exceeded') ||\n message.includes('unauthorized') ||\n message.includes('k8s api error 401')\n ) {\n return false;\n }\n return [\n 'sandbox not found',\n 'sandbox is not running',\n 'sandbox service not available yet',\n 'sandbox failed',\n 'sandbox startup timed out',\n 'assistant service did not become healthy',\n 'proxy error: 404',\n 'proxy error: 502',\n 'proxy error: 503',\n 'unable to connect',\n 'image pull',\n 'container failed',\n 'bootstrap failed',\n // Transient network errors from the browser fetch — gateway CORS preflight\n // failures, mid-stream resets, and Cloudflare 524s all surface as\n // \"Failed to fetch\" via TypeError. They're worth retrying on a clean\n // runtime since the underlying sandbox state is unaffected.\n 'failed to fetch',\n 'cf-proxy timeout',\n // Subgraph returned 500 with a generic message — gateway returns this as\n // a GraphQL error rather than an HTTP error. The actual underlying cause\n // (e.g., transient Prisma timeout) is recoverable, but a fresh sandbox\n // may be needed.\n 'unexpected error',\n ].some((fragment) => message.includes(fragment));\n}\n\n/**\n * Returns a memoized `AssistantTransport` wired to the BigConsole sandbox\n * assistant agent. The sandbox + session are cached in refs so follow-up turns\n * reuse the warm environment for the lifetime of the host shell.\n */\nexport function useSandboxAssistantTransport(): AssistantTransport {\n const { getAccessToken, getWorkspaceToken, userId, workspaceId: ctxWorkspaceId } = useAuthToken();\n\n // Rehydrate the sandbox + session ids persisted by the previous page\n // lifecycle. These were being WRITTEN to sessionStorage but never read back,\n // so every reload silently opened a brand-new agent session: the chat looked\n // empty AND the agent genuinely lost the conversation (it could no longer\n // resolve \"that datasink\" / \"the dashboard you just made\").\n //\n // Restoring both together is what makes history real rather than cosmetic —\n // the transcript we replay into the UI is the same session the agent will\n // keep reasoning over. A stale/expired sandbox is not a problem: `sendPrompt`\n // already treats that as recoverable, drops the refs, and retries clean.\n const [initialSandboxId, initialSessionId, initialConversationId] = useMemo(\n () => [readStoredId(SANDBOX_ID_KEY), readStoredId(SESSION_ID_KEY), readStoredId(CONVERSATION_ID_KEY)] as const,\n []\n );\n\n const sandboxIdRef = useRef<string | null>(initialSandboxId);\n const sessionIdRef = useRef<string | null>(initialSessionId);\n const conversationIdRef = useRef<string | null>(initialConversationId);\n /**\n * Transcript to feed the agent on its next prompt.\n *\n * A chat can outlive the agent that produced it: the transcript is durable,\n * the sandbox session is not. Showing the messages while the agent silently\n * remembers nothing is the worst of both worlds — ask it to \"add a widget to\n * that dashboard\" and it has no idea what \"that\" is. So when a chat is\n * resumed after its agent is gone, replay the conversation into its first\n * prompt.\n */\n const replayRef = useRef<string | null>(null);\n\n const persistSandboxId = useCallback((id: string | null) => {\n sandboxIdRef.current = id;\n writeStoredId(SANDBOX_ID_KEY, id);\n }, []);\n\n const persistSessionId = useCallback((id: string | null) => {\n sessionIdRef.current = id;\n writeStoredId(SESSION_ID_KEY, id);\n }, []);\n\n const persistConversationId = useCallback((id: string | null) => {\n conversationIdRef.current = id;\n writeStoredId(CONVERSATION_ID_KEY, id);\n }, []);\n\n const ensureRuntime = useCallback(\n async (\n workspaceId: string,\n authContext: AssistantSandboxAuthContext\n ): Promise<{ sandboxId: string; sessionId: string }> => {\n let sandboxId = sandboxIdRef.current;\n console.log('[BigConsole-Assistant] ensureRuntime start', { sandboxId, workspaceId });\n if (!sandboxId) {\n if (!getAccessToken()) {\n throw new Error('The assistant requires an authenticated session. Please sign in again.');\n }\n console.log('[BigConsole-Assistant] findExistingSandbox called');\n sandboxId = await findExistingSandbox(workspaceId, MODE, authContext);\n console.log('[BigConsole-Assistant] findExistingSandbox result', { sandboxId });\n\n if (sandboxId) {\n try {\n console.log('[BigConsole-Assistant] waitForSandboxReady called (reused)', { sandboxId });\n await waitForSandboxReady(sandboxId, workspaceId, authContext);\n console.log('[BigConsole-Assistant] waitForSandboxReady done (reused)', { sandboxId });\n console.log('[BigConsole-Assistant] waitForAssistantServiceReady called (reused)', { sandboxId });\n await waitForAssistantServiceReady(sandboxId, workspaceId, MODE, authContext);\n console.log('[BigConsole-Assistant] waitForAssistantServiceReady done (reused)', { sandboxId });\n } catch (error) {\n console.warn('[BigConsole-Assistant] existing sandbox unusable, falling back to fresh sandbox', {\n sandboxId,\n error: error instanceof Error ? error.message : String(error),\n });\n sandboxId = null;\n }\n }\n\n if (!sandboxId) {\n console.log('[BigConsole-Assistant] createAssistantSandbox called');\n sandboxId = await createAssistantSandbox(MODE, workspaceId, authContext);\n console.log('[BigConsole-Assistant] createAssistantSandbox result', { sandboxId });\n console.log('[BigConsole-Assistant] waitForSandboxReady called (fresh)', { sandboxId });\n await waitForSandboxReady(sandboxId, workspaceId, authContext);\n console.log('[BigConsole-Assistant] waitForSandboxReady done (fresh)', { sandboxId });\n console.log('[BigConsole-Assistant] waitForAssistantServiceReady called (fresh)', { sandboxId });\n await waitForAssistantServiceReady(sandboxId, workspaceId, MODE, authContext);\n console.log('[BigConsole-Assistant] waitForAssistantServiceReady done (fresh)', { sandboxId });\n }\n\n persistSandboxId(sandboxId);\n }\n\n let sessionId = sessionIdRef.current;\n console.log('[BigConsole-Assistant] session check', { sessionId, sandboxId });\n if (!sessionId) {\n console.log('[BigConsole-Assistant] createAssistantSession called', { sandboxId, workspaceId });\n const result = await createAssistantSession(sandboxId, workspaceId, MODE, authContext);\n sessionId = result.sessionId;\n persistSessionId(sessionId);\n }\n\n return { sandboxId, sessionId };\n },\n [getAccessToken]\n );\n\n const sendPrompt = useCallback(\n async ({ prompt, onProgress, signal }: AssistantSendArgs): Promise<{ text: string }> => {\n const workspaceId = getWorkspaceId(ctxWorkspaceId);\n console.log('[BigConsole-Assistant] sendPrompt called', {\n promptLength: prompt.length,\n workspaceId,\n hasCtxWorkspaceId: !!ctxWorkspaceId,\n authContextKeys: {\n hasAccessToken: !!getAccessToken(),\n hasWorkspaceToken: !!getWorkspaceToken(),\n hasUserId: !!userId,\n },\n locationSearch: window.location.search,\n });\n if (!workspaceId) {\n throw new Error('The assistant needs an active workspace. Open a workspace and try again.');\n }\n const authContext: AssistantSandboxAuthContext = {\n accessToken: getAccessToken(),\n workspaceToken: getWorkspaceToken(),\n userId,\n organizationId: getOrganizationId(),\n };\n console.log('[BigConsole-Assistant] authContext prepared', {\n hasAccessToken: !!authContext.accessToken,\n hasWorkspaceToken: !!authContext.workspaceToken,\n hasUserId: !!authContext.userId,\n hasOrgId: !!authContext.organizationId,\n });\n\n // Drive the live preview panel. The agent has no event stream, so the\n // narration IS the signal: the store parses it into a DataSink → Dashboard\n // → Parser → Widget rail. Fed here rather than in the widget because the\n // host owns this transport, so no fe-libs change is needed.\n const runStore = useAssistantRunStore.getState();\n runStore.startRun(prompt);\n const reportProgress = (partial: string): void => {\n onProgress(partial);\n useAssistantRunStore.getState().applyProgress(partial);\n };\n\n const run = async (attempt: 1 | 2): Promise<{ text: string }> => {\n try {\n console.log('[BigConsole-Assistant] run attempt', attempt);\n const { sandboxId, sessionId } = await ensureRuntime(workspaceId, authContext);\n console.log('[BigConsole-Assistant] ensureRuntime resolved', { sandboxId, sessionId });\n\n // Resuming a chat whose agent session is gone: hand the agent the\n // earlier transcript once, on the first prompt of the resumed chat, so\n // it answers with that context instead of from a blank slate. Consumed\n // on success — never replayed twice into the same session.\n const replay = replayRef.current;\n const agentPrompt = replay ? `${replay}\\n\\n---\\n\\n${prompt}` : prompt;\n\n const startedAt = Date.now();\n console.log('[BigConsole-Assistant] calling sendAssistantPromptAsync', {\n sandboxId,\n workspaceId,\n sessionId,\n promptLength: agentPrompt.length,\n replayed: Boolean(replay),\n });\n await sendAssistantPromptAsync(\n sandboxId,\n workspaceId,\n sessionId,\n agentPrompt,\n MODE,\n gatherPageContext(),\n authContext\n );\n\n const timeoutAt = Date.now() + STREAM_BUDGET_MS;\n let lastTtlExtensionAt = Date.now();\n let lastContent = '';\n let lastContentChangeAt = Date.now();\n let progress = buildProgress([], startedAt);\n\n while (Date.now() < timeoutAt) {\n if (signal.aborted) throw new Error('Cancelled');\n\n const messages = await getAssistantMessages(sandboxId, workspaceId, sessionId, authContext, 50);\n console.log('[BigConsole-Assistant] poll', {\n elapsedMs: Date.now() - startedAt,\n messageCount: messages.length,\n firstFewRoles: messages.slice(0, 3).map((m) => getMessageRole(m)),\n firstFewTimestamps: messages.slice(0, 3).map((m) => getRawMessageCreatedAt(m)),\n });\n progress = buildProgress(messages, startedAt, lastContent, lastContentChangeAt);\n console.log('[BigConsole-Assistant] progress', {\n contentPreview: progress.content.slice(0, 100),\n done: progress.done,\n lastContentChangeAt: Date.now() - lastContentChangeAt,\n });\n if (progress.content !== lastContent) {\n lastContent = progress.content;\n lastContentChangeAt = Date.now();\n }\n reportProgress(sanitize(progress.content));\n if (progress.done) {\n console.log('[BigConsole-Assistant] progress.done=true, breaking poll loop');\n break;\n }\n\n if (Date.now() - lastTtlExtensionAt > TTL_EXTEND_INTERVAL_MS) {\n await extendAssistantSandboxTTL(sandboxId, workspaceId, 600, authContext).catch(() => undefined);\n lastTtlExtensionAt = Date.now();\n }\n\n await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));\n }\n\n if (!progress.done) {\n // Do NOT say \"please try again\". We stopped watching; the agent did\n // not stop working, and anything it already created is real. Telling\n // people to retry is how you get duplicate dashboards.\n throw new Error(\n 'I stopped waiting for a reply, but I may still be working — anything I already created will be there. Check your dashboards and data sinks before asking again, so you do not end up with duplicates.'\n );\n }\n\n const reply = sanitize(progress.content);\n\n // An empty reply is a FAILED turn, not a successful one.\n //\n // `buildProgress` gives up and reports `done` when the agent has said\n // nothing for 15s, which is what happens when the runtime cannot serve\n // the turn at all (e.g. the sandbox quota is exhausted). Returning that\n // as a success showed the user a blank assistant bubble and — once\n // history became durable — wrote an empty transcript into it, leaving\n // a titled chat with nothing inside. Fail loudly and save nothing.\n if (!reply.trim()) {\n throw new Error(\n 'I could not produce a reply — the assistant runtime did not respond. It may be out of capacity right now. Nothing was changed; please try again shortly.'\n );\n }\n\n replayRef.current = null;\n\n // Persist the completed turn. Failing to save must not fail the turn —\n // the user got their answer, and the work the agent did is already real.\n try {\n const conversation = await saveAssistantTurn(\n {\n conversationId: conversationIdRef.current,\n prompt,\n reply,\n agentSessionId: sessionId,\n },\n workspaceId,\n authContext\n );\n persistConversationId(conversation.id);\n } catch (error) {\n console.warn('[BigConsole-Assistant] could not save turn to history', {\n error: error instanceof Error ? error.message : String(error),\n });\n }\n\n return { text: reply };\n } catch (error) {\n console.error('[BigConsole-Assistant] run error', {\n attempt,\n error: error instanceof Error ? error.message : String(error),\n stack: error instanceof Error ? error.stack : undefined,\n sandboxId: sandboxIdRef.current,\n sessionId: sessionIdRef.current,\n });\n // A stale/expired sandbox or session is recoverable — drop the warm\n // refs and retry once from a clean runtime.\n if (attempt === 1 && isRecoverable(error)) {\n persistSandboxId(null);\n persistSessionId(null);\n return run(2);\n }\n throw error;\n }\n };\n\n try {\n const result = await run(1);\n useAssistantRunStore.getState().finishRun(null);\n return result;\n } catch (error) {\n useAssistantRunStore.getState().finishRun(error instanceof Error ? error.message : String(error));\n throw error;\n }\n },\n [\n ctxWorkspaceId,\n ensureRuntime,\n getAccessToken,\n getWorkspaceToken,\n userId,\n persistSandboxId,\n persistSessionId,\n persistConversationId,\n ]\n );\n\n // ── Durable history (wspace-conversations) ───────────────────────────────\n //\n // The agent's own session lives in a sandbox with a 10-minute TTL and no\n // persistent volume, so it CANNOT be the store of record for a transcript the\n // user expects to keep. Every completed turn is written to wspace-conversations\n // instead, tagged with the product, so history is durable AND product-scoped —\n // a BigConsole chat can never surface in another product's panel.\n //\n // Two ids, doing different jobs:\n // conversationId — the durable chat. What History lists, and what the widget\n // treats as \"the session\".\n // sessionId — the LIVE agent session inside the sandbox. Ephemeral; a\n // hint stored on the conversation so a still-warm agent can\n // be resumed.\n\n const authFor = useCallback(\n (): AssistantSandboxAuthContext => ({\n accessToken: getAccessToken(),\n workspaceToken: getWorkspaceToken(),\n userId,\n organizationId: getOrganizationId(),\n }),\n [getAccessToken, getWorkspaceToken, userId]\n );\n\n const buildReplay = useCallback((messages: AssistantHistoryMessage[]): string | null => {\n if (messages.length === 0) return null;\n const transcript = messages\n .map((message) => `${message.role === 'user' ? 'User' : 'Assistant'}: ${message.content}`)\n .join('\\n\\n')\n .slice(-REPLAY_MAX_CHARS);\n\n return [\n 'You are resuming an earlier conversation. What follows is what was said in it — treat it as your own memory and continue seamlessly. Do not mention this replay, and do not redo work that was already completed.',\n '--- earlier in this conversation ---',\n transcript,\n '--- end ---',\n ].join('\\n\\n');\n }, []);\n\n const mapConversationMessages = useCallback(\n (messages: AssistantHistoryTurnMessage[]): AssistantHistoryMessage[] =>\n messages.map((message) => ({\n id: message.id,\n role: message.role === 'ASSISTANT' ? ('assistant' as const) : ('user' as const),\n content: sanitize(message.content),\n })),\n []\n );\n\n /**\n * Adopt a conversation: show its transcript, and line the agent up to continue\n * it — resuming the live session when one survives, replaying the transcript\n * when it does not.\n */\n const adoptConversation = useCallback(\n async (\n conversation: AssistantConversationSummary,\n workspaceId: string,\n auth: AssistantSandboxAuthContext\n ): Promise<AssistantHistoryMessage[]> => {\n const raw = await getAssistantConversationMessages(conversation.id, workspaceId, auth, HISTORY_MESSAGE_LIMIT);\n const messages = mapConversationMessages(raw);\n\n persistConversationId(conversation.id);\n\n if (conversation.agentSessionId) {\n // The agent may still be warm — adopt its session. If it has in fact\n // expired, sendPrompt's recoverable-retry path mints a fresh one.\n persistSessionId(conversation.agentSessionId);\n replayRef.current = null;\n } else {\n persistSessionId(null);\n replayRef.current = buildReplay(messages);\n }\n\n return messages;\n },\n [mapConversationMessages, persistConversationId, persistSessionId, buildReplay]\n );\n\n const loadHistory = useCallback(async (): Promise<AssistantHistoryMessage[]> => {\n const workspaceId = getWorkspaceId(ctxWorkspaceId);\n if (!workspaceId || !getAccessToken()) return [];\n const auth = authFor();\n\n try {\n const conversations = await listAssistantConversations(workspaceId, auth, SESSION_LIST_LIMIT);\n\n // Reopen the chat the user was in; failing that, their most recent one, so\n // a fresh login lands them back where they left off rather than in a blank\n // chat with their history hidden behind a menu.\n const current = conversationIdRef.current;\n const target = conversations.find((conversation) => conversation.id === current) ?? conversations[0];\n if (!target) return [];\n\n return await adoptConversation(target, workspaceId, auth);\n } catch (error) {\n console.warn('[BigConsole-Assistant] could not restore history', {\n error: error instanceof Error ? error.message : String(error),\n });\n return [];\n }\n }, [ctxWorkspaceId, getAccessToken, authFor, adoptConversation]);\n\n const listSessions = useCallback(async (): Promise<AssistantSessionSummaryLocal[]> => {\n const workspaceId = getWorkspaceId(ctxWorkspaceId);\n if (!workspaceId || !getAccessToken()) return [];\n\n try {\n const conversations = await listAssistantConversations(workspaceId, authFor(), SESSION_LIST_LIMIT);\n // Titles come from the store, so listing is ONE round-trip — no per-chat\n // probing, which is what used to make opening History feel slow.\n return conversations.map((conversation) => ({\n id: conversation.id,\n title: conversation.title?.trim() || 'New chat',\n updatedAt: Date.parse(conversation.updatedAt) || undefined,\n active: conversation.id === conversationIdRef.current,\n }));\n } catch {\n return [];\n }\n }, [ctxWorkspaceId, getAccessToken, authFor]);\n\n /**\n * Start a new chat — instantly, and with no backend call.\n *\n * Both ids are simply detached: the agent session is created lazily on the next\n * prompt, and the conversation row by the first saveAssistantTurn. Nothing to\n * wait for, and no empty conversations left behind for chats nobody used.\n */\n const newSession = useCallback(async (): Promise<void> => {\n persistConversationId(null);\n persistSessionId(null);\n replayRef.current = null;\n return Promise.resolve();\n }, [persistConversationId, persistSessionId]);\n\n const deleteSession = useCallback(\n async (conversationId: string): Promise<void> => {\n const workspaceId = getWorkspaceId(ctxWorkspaceId);\n if (!workspaceId) return;\n\n await deleteAssistantConversation(conversationId, workspaceId, authFor());\n\n // Deleting the chat you are looking at leaves you in a fresh one.\n if (conversationIdRef.current === conversationId) {\n persistConversationId(null);\n persistSessionId(null);\n replayRef.current = null;\n }\n },\n [ctxWorkspaceId, authFor, persistConversationId, persistSessionId]\n );\n\n const selectSession = useCallback(\n async (conversationId: string): Promise<AssistantHistoryMessage[]> => {\n const workspaceId = getWorkspaceId(ctxWorkspaceId);\n if (!workspaceId) return [];\n const auth = authFor();\n\n const conversations = await listAssistantConversations(workspaceId, auth, SESSION_LIST_LIMIT);\n const target = conversations.find((conversation) => conversation.id === conversationId);\n if (!target) return [];\n\n return adoptConversation(target, workspaceId, auth);\n },\n [ctxWorkspaceId, authFor, adoptConversation]\n );\n\n return useMemo<AssistantTransport>(\n () => ({ sendPrompt, loadHistory, listSessions, newSession, deleteSession, selectSession }),\n [sendPrompt, loadHistory, listSessions, newSession, deleteSession, selectSession]\n );\n}\n"],"mappings":";;;;;;;AA0FA,IAAM,IAAsB,aAatB,KAAmB,MACnB,KAAmB,MACnB,KAAyB,KAIzB,IAAwB,KAExB,IAAqB,IAMrB,IAAmB,KAEnB,IAAiB,2BACjB,IAAiB,2BAEjB,IAAsB;AAE5B,SAAS,EAAa,GAA4B;AAChD,KAAI;AACF,SAAO,OAAO,eAAe,QAAQ,EAAI;SACnC;AAEN,SAAO;;;AAIX,SAAS,EAAc,GAAa,GAAyB;AAC3D,KAAI;AACF,EAAI,IAAI,OAAO,eAAe,QAAQ,GAAK,EAAG,GACzC,OAAO,eAAe,WAAW,EAAI;SACpC;;AAOV,SAAS,EAAuB,GAA+C;AAC7E,KAAI;EACF,IAAM,IACJ,MAAQ,gBAAgB,uCAAuC,yCAC3D,IAAqB,aAAa,QAAQ,EAAiB;AACjE,MAAI,EAAoB,QAAO;EAE/B,IAAM,IAAkB,eAAe,QAAQ,oBAAoB;AACnE,MAAI,CAAC,EAAiB,QAAO;EAC7B,IAAM,IAAM,aAAa,QAAQ,QAAQ,EAAgB,UAAU;AAGnE,SAFK,IACW,KAAK,MAAM,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AA2B,GAAa,GAAM,EAAmB,EAChE,MAAM,MAAiB,EAAa,OAAO,EAAe;AAGvF,SAFK,IAEE,EAAkB,GAAQ,GAAa,EAAK,GAF/B,EAAE;IAIxB;EAAC;EAAgB;EAAS;EAAkB,CAC7C;AAED,QAAO,SACE;EAAE;EAAY;EAAa;EAAc;EAAY;EAAe;EAAe,GAC1F;EAAC;EAAY;EAAa;EAAc;EAAY;EAAe;EAAc,CAClF"}
1
+ {"version":3,"file":"createSandboxAssistantTransport.js","names":[],"sources":["../../../src/bigconsole/assistant/createSandboxAssistantTransport.ts"],"sourcesContent":["/**\n * BigConsole adapter for the shared fe-libs AssistantWidget.\n *\n * The floating widget (fe-libs, Layer 1) is backend-agnostic — it calls an\n * injected `AssistantTransport`. This hook builds a transport that drives the\n * sandbox AI assistant (combined `assistant` mode = docs Q&A + api-calls): it\n * provisions/reuses a sandbox, opens a session, dispatches the prompt async,\n * then polls for the streamed answer. The agent introspects the GraphQL schema\n * and performs API calls on the user's behalf using their workspace token,\n * contextual to the current screen (via `gatherPageContext`).\n *\n * This is a faithful port of microfe-vibecontrols'\n * `services/createSandboxAssistantTransport.ts`; the only product-specific\n * difference lives in `assistantApi.createAssistantSandbox`\n * (`AI_ASSISTANT_PRODUCT=bigconsole`).\n */\n\nimport { useCallback, useMemo, useRef } from 'react';\nimport { useAuthToken } from '@burdenoff/fe-libs/shared/providers/shell';\nimport {\n createAssistantSandbox,\n createAssistantSession,\n extendAssistantSandboxTTL,\n findExistingSandbox,\n getAssistantMessages,\n sendAssistantPromptAsync,\n waitForAssistantServiceReady,\n waitForSandboxReady,\n} from './assistantApi';\nimport { buildAttachmentBlock } from './attachmentExtract';\nimport { useAssistantRunStore } from './assistantRunStore';\nimport {\n type AssistantConversationSummary,\n type AssistantHistoryTurnMessage,\n deleteAssistantConversation,\n getAssistantConversationMessages,\n listAssistantConversations,\n saveAssistantTurn,\n} from './conversationHistoryApi';\nimport { gatherPageContext } from './pageContext';\nimport type { AssistantMode, AssistantRawMessage, AssistantRawMessagePart, AssistantSandboxAuthContext } from './types';\n\n/**\n * Locally-defined mirror of the fe-libs `AssistantTransport` contract.\n *\n * Intentionally NOT imported from `@burdenoff/fe-libs`: microfe's tsconfig maps\n * `@burdenoff/fe-libs/*` to fe-libs *source*, so vite-plugin-dts would rewrite a\n * cross-package type used in this hook's public signature to a broken\n * source-relative path in the emitted `.d.ts`. Structural typing makes this\n * shape assignable to fe-libs' `AssistantTransport` at the call site\n * (bigconsole-app's AppShell), which is where compatibility is enforced.\n */\ninterface AssistantSendArgs {\n prompt: string;\n /** Files attached via the widget's upload button (fe-libs carries the raw\n * File[]; we extract + fold a capped preview into the agent prompt here). */\n attachments?: File[];\n onProgress: (partialText: string) => void;\n signal: AbortSignal;\n}\n\n/** Mirror of fe-libs' `AssistantWidgetMessage` (see note above on why). */\ninterface AssistantHistoryMessage {\n id: string;\n role: 'user' | 'assistant';\n content: string;\n pending?: boolean;\n error?: boolean;\n}\n\n/** Mirror of fe-libs' `AssistantSessionSummary` (see note above on why). */\ninterface AssistantSessionSummaryLocal {\n id: string;\n title: string;\n updatedAt?: number;\n active?: boolean;\n}\n\nexport interface AssistantTransport {\n sendPrompt: (args: AssistantSendArgs) => Promise<{ text: string }>;\n loadHistory: () => Promise<AssistantHistoryMessage[]>;\n listSessions: () => Promise<AssistantSessionSummaryLocal[]>;\n newSession: () => Promise<void>;\n deleteSession: (sessionId: string) => Promise<void>;\n selectSession: (sessionId: string) => Promise<AssistantHistoryMessage[]>;\n}\n\n// BigConsole still boots the manually-tagged ACA image\n// `alpha-delegated-auth-v11` for the assistant sandbox. The historical\n// platform notes show that this image line reliably supports `api-calls`, while\n// the combined `assistant` mode depends on newer image contracts that are not\n// yet guaranteed on this tag. Use `api-calls` here so the assistant can execute\n// workspace GraphQL operations end-to-end right now. Once the underlying image\n// line is rebuilt and verified for combined mode, this can be switched back.\nconst MODE: AssistantMode = 'api-calls';\n// How long the UI will follow a single turn.\n//\n// This was 180s, which was SHORTER THAN THE WORK. A full \"create a school\n// attendance dashboard\" build — datasink → dashboard → parser → widget, each a\n// separate gateway call preceded by a model round-trip — measured 229s in prod.\n// So the agent finished, the dashboard genuinely existed, and the user was still\n// shown \"the assistant timed out\". That is worse than cosmetic: people retry and\n// end up with duplicate dashboards.\n//\n// 7 minutes covers the observed worst case with headroom. It costs nothing on\n// fast turns (we stop the moment the turn reports done), and the backend keeps\n// pace — the sandbox TTL is extended every TTL_EXTEND_INTERVAL_MS.\nconst STREAM_BUDGET_MS = 420_000;\nconst POLL_INTERVAL_MS = 1500;\nconst TTL_EXTEND_INTERVAL_MS = 30_000;\n// Raw agent messages per restore. The agent emits one message per internal\n// step, so a handful of turns is already dozens of messages — this is a cap on\n// the RAW fetch, not on the number of restored turns.\nconst HISTORY_MESSAGE_LIMIT = 200;\n/** Chats shown in History. Titles come from the store, so listing is one query. */\nconst SESSION_LIST_LIMIT = 25;\n/**\n * Cap on the transcript replayed into a resumed agent session. Long enough to\n * carry the ids and decisions that make \"that dashboard\" resolvable, short\n * enough not to crowd out the actual prompt.\n */\nconst REPLAY_MAX_CHARS = 6000;\n\nconst SANDBOX_ID_KEY = 'bc-assistant-sandbox-id';\nconst SESSION_ID_KEY = 'bc-assistant-session-id';\n/** The durable chat. This is the identity History lists. */\nconst CONVERSATION_ID_KEY = 'bc-assistant-conversation-id';\n\nfunction readStoredId(key: string): string | null {\n try {\n return window.sessionStorage.getItem(key);\n } catch {\n // sessionStorage unavailable (private mode) — degrade to a fresh session.\n return null;\n }\n}\n\nfunction writeStoredId(key: string, id: string | null): void {\n try {\n if (id) window.sessionStorage.setItem(key, id);\n else window.sessionStorage.removeItem(key);\n } catch {\n // Non-fatal: we simply lose cross-reload continuity.\n }\n}\n\n// ── Context helpers (mirror vibecontrols' resolution) ────────────────\n\nfunction getProfileContextValue(key: 'workspaceId' | 'organizationId'): string {\n try {\n const activeContextKey =\n key === 'workspaceId' ? 'burdenoff-active-context-workspace' : 'burdenoff-active-context-organization';\n const activeContextValue = localStorage.getItem(activeContextKey);\n if (activeContextValue) return activeContextValue;\n\n const activeProfileId = sessionStorage.getItem('bf-active-profile');\n if (!activeProfileId) return '';\n const raw = localStorage.getItem(`bf-p-${activeProfileId}-context`);\n if (!raw) return '';\n const context = JSON.parse(raw) as { workspaceId?: string; organizationId?: string };\n return context[key] ?? '';\n } catch {\n return '';\n }\n}\n\nfunction getWorkspaceId(fallback: string | null): string {\n const params = new URLSearchParams(window.location.search);\n return params.get('workspace') ?? getProfileContextValue('workspaceId') ?? fallback ?? '';\n}\n\nfunction getOrganizationId(): string {\n const params = new URLSearchParams(window.location.search);\n return params.get('org') ?? getProfileContextValue('organizationId');\n}\n\n// ── Message-progress helpers (pure; mirror vibecontrols) ─────────────\n\nfunction getMessageRole(message: AssistantRawMessage): string | undefined {\n // Check nested format first, then flat format\n return message.info?.role ?? message.role;\n}\n\nfunction getRawMessageCreatedAt(message: AssistantRawMessage): number {\n // Check nested format first (epoch ms), then flat format (ISO string or epoch ms)\n const nested = message.info?.time?.created;\n if (nested !== undefined) return nested;\n const flat = message.createdAt;\n if (flat === undefined) return 0;\n // If it's a string (ISO), parse it; otherwise treat as epoch ms\n if (typeof flat === 'string') {\n const parsed = Date.parse(flat);\n return isNaN(parsed) ? 0 : parsed;\n }\n return flat;\n}\n\nfunction getMessageCompleted(message: AssistantRawMessage): number | undefined {\n // Check nested format first, then flat format\n const nested = message.info?.time?.completed;\n if (nested !== undefined) return nested;\n const flat = message.completedAt;\n if (flat === undefined) return undefined;\n if (typeof flat === 'string') {\n const parsed = Date.parse(flat);\n return isNaN(parsed) ? undefined : parsed;\n }\n return flat;\n}\n\nfunction getAssistantText(message: AssistantRawMessage): string {\n // Check parts format first (nested), then flat content\n const parts = message.parts ?? [];\n const textFromParts = (parts ?? [])\n .filter((part) => part.type === 'text' && typeof part.text === 'string')\n .map((part) => part.text?.trim() ?? '')\n .filter(Boolean)\n .join('\\n');\n if (textFromParts) return textFromParts;\n // Fallback to flat content field\n return typeof message.content === 'string' ? message.content.trim() : '';\n}\n\n// Friendly, human-readable labels for the agent's tools so the progress line\n// reads like \"Searching the schema…\" instead of \"Running: bash\". The agent sets\n// a `description` on every bash call (e.g. \"Search for sales-related types in\n// workspace schema\") and a todo list on todowrite — surface those directly.\nconst TOOL_LABELS: Record<string, string> = {\n bash: 'Running a command',\n webfetch: 'Fetching a page',\n 'file.read': 'Reading files',\n 'file.write': 'Writing files',\n 'file.edit': 'Editing files',\n 'file.find.text': 'Searching the code',\n 'file.find.file': 'Looking for files',\n todowrite: 'Planning the steps',\n todoread: 'Reviewing the plan',\n};\n\nfunction asRecord(value: unknown): Record<string, unknown> | undefined {\n return typeof value === 'object' && value !== null ? (value as Record<string, unknown>) : undefined;\n}\n\n/** Best-effort human summary of what a single tool part is doing right now. */\nfunction describeToolPart(part: AssistantRawMessagePart): string {\n const tool = part.tool ?? 'tool';\n const input = asRecord(part.state?.input);\n\n // bash carries a plain-English `description` of the step — the best signal.\n const description = input?.description;\n if (typeof description === 'string' && description.trim()) return description.trim();\n\n // todowrite carries the todo list — surface the item being worked on.\n const todos = input?.todos;\n if (Array.isArray(todos)) {\n const active = todos.find((todo) => asRecord(todo)?.status === 'in_progress') ?? todos[0];\n const content = asRecord(active)?.content;\n if (typeof content === 'string' && content.trim()) return content.trim();\n }\n\n return TOOL_LABELS[tool] ?? `Running ${tool}`;\n}\n\nfunction getToolProgress(message: AssistantRawMessage): string[] {\n const parts = message.parts ?? [];\n return parts\n .filter((part) => part.type === 'tool' && part.tool)\n .map((part) => {\n const status = part.state?.status ?? 'running';\n const label = describeToolPart(part);\n if (status === 'completed') return `✓ ${label}`;\n if (status === 'failed') return `⚠ ${label}`;\n return `⏳ ${label}…`;\n });\n}\n\nfunction buildProgress(\n messages: AssistantRawMessage[],\n sinceMs: number,\n previousContent?: string,\n previousContentAtMs?: number\n): { content: string; done: boolean } {\n const relevant = messages\n .filter((message) => getMessageRole(message) === 'assistant' && getRawMessageCreatedAt(message) >= sinceMs)\n .sort((left, right) => getRawMessageCreatedAt(left) - getRawMessageCreatedAt(right));\n\n // Debug: log message filtering when no relevant messages found\n if (relevant.length === 0 && messages.length > 0) {\n console.log('[BigConsole-Assistant] buildProgress: no relevant messages', {\n totalMessages: messages.length,\n sinceMs,\n messageRoles: messages.map((m) => getMessageRole(m)),\n messageTimestamps: messages.map((m) => getRawMessageCreatedAt(m)),\n });\n }\n\n let content: string;\n let done: boolean;\n\n if (relevant.length === 0) {\n content = '';\n // Staleness fallback: if no messages have appeared after 15+ seconds of polling,\n // treat the response as complete even when messages get filtered out\n // (e.g., due to timestamp skew or role mismatch).\n done =\n previousContent === content && previousContentAtMs !== undefined && Date.now() - previousContentAtMs >= 15_000;\n } else {\n const latest = relevant[relevant.length - 1]!;\n\n // ACCUMULATE the run, don't just show its last line.\n //\n // The agent emits a message per step, and it now narrates each one and prints\n // a link the moment a create lands (\"✅ Data sink created — [Open …](/…)\").\n // Showing only the newest message threw all of that away a second later: the\n // user saw a lone \"Thinking…\" and none of the links they were promised. Join\n // the whole run instead, so the panel reads as a live account of what is\n // happening and every link stays on screen.\n const narration = relevant.map(getAssistantText).filter(Boolean);\n const toolProgress = getToolProgress(latest);\n content = [...narration, ...toolProgress].join('\\n\\n');\n\n const officiallyDone = Boolean(getMessageCompleted(latest)) && content.length > 0;\n\n // A tool that is still running is proof the turn is alive, so never let the\n // staleness fallback fire underneath it. A single gateway call can sit on the\n // same \"⏳ Creating the data sink…\" line for far longer than the old 15s\n // window, which would have declared the turn finished mid-build.\n const hasRunningTool = (latest.parts ?? []).some(\n (part) => part.type === 'tool' && part.state?.status !== 'completed' && part.state?.status !== 'failed'\n );\n\n const staleDone =\n !officiallyDone &&\n !hasRunningTool &&\n previousContent === content &&\n previousContentAtMs !== undefined &&\n Date.now() - previousContentAtMs >= 45_000;\n\n done = officiallyDone || staleDone;\n }\n\n return { content, done };\n}\n\nfunction sanitize(response: string): string {\n return response\n .replace(/(Authorization\\s*:\\s*Bearer\\s+)[^\\s\\n]+/gi, '$1[REDACTED]')\n .replace(/(X-Workspace-Authorization\\s*:\\s*Bearer\\s+)[^\\s\\n]+/gi, '$1[REDACTED]')\n .replace(/\\beyJ[A-Za-z0-9_-]+\\.[A-Za-z0-9._-]+\\.[A-Za-z0-9._-]+\\b/g, '[REDACTED_JWT]')\n .replace(/\\bsk-ant-[A-Za-z0-9-]+\\b/g, '[REDACTED_API_KEY]');\n}\n\nfunction isRecoverable(error: unknown): boolean {\n const message = error instanceof Error ? error.message.toLowerCase() : String(error).toLowerCase();\n if (\n message.includes('rate limit exceeded') ||\n message.includes('unauthorized') ||\n message.includes('k8s api error 401')\n ) {\n return false;\n }\n return [\n 'sandbox not found',\n 'sandbox is not running',\n 'sandbox service not available yet',\n 'sandbox failed',\n 'sandbox startup timed out',\n 'assistant service did not become healthy',\n 'proxy error: 404',\n 'proxy error: 502',\n 'proxy error: 503',\n 'unable to connect',\n 'image pull',\n 'container failed',\n 'bootstrap failed',\n // Transient network errors from the browser fetch — gateway CORS preflight\n // failures, mid-stream resets, and Cloudflare 524s all surface as\n // \"Failed to fetch\" via TypeError. They're worth retrying on a clean\n // runtime since the underlying sandbox state is unaffected.\n 'failed to fetch',\n 'cf-proxy timeout',\n // Subgraph returned 500 with a generic message — gateway returns this as\n // a GraphQL error rather than an HTTP error. The actual underlying cause\n // (e.g., transient Prisma timeout) is recoverable, but a fresh sandbox\n // may be needed.\n 'unexpected error',\n ].some((fragment) => message.includes(fragment));\n}\n\n/**\n * Returns a memoized `AssistantTransport` wired to the BigConsole sandbox\n * assistant agent. The sandbox + session are cached in refs so follow-up turns\n * reuse the warm environment for the lifetime of the host shell.\n */\nexport function useSandboxAssistantTransport(): AssistantTransport {\n const { getAccessToken, getWorkspaceToken, userId, workspaceId: ctxWorkspaceId } = useAuthToken();\n\n // Rehydrate the sandbox + session ids persisted by the previous page\n // lifecycle. These were being WRITTEN to sessionStorage but never read back,\n // so every reload silently opened a brand-new agent session: the chat looked\n // empty AND the agent genuinely lost the conversation (it could no longer\n // resolve \"that datasink\" / \"the dashboard you just made\").\n //\n // Restoring both together is what makes history real rather than cosmetic —\n // the transcript we replay into the UI is the same session the agent will\n // keep reasoning over. A stale/expired sandbox is not a problem: `sendPrompt`\n // already treats that as recoverable, drops the refs, and retries clean.\n const [initialSandboxId, initialSessionId, initialConversationId] = useMemo(\n () => [readStoredId(SANDBOX_ID_KEY), readStoredId(SESSION_ID_KEY), readStoredId(CONVERSATION_ID_KEY)] as const,\n []\n );\n\n const sandboxIdRef = useRef<string | null>(initialSandboxId);\n const sessionIdRef = useRef<string | null>(initialSessionId);\n const conversationIdRef = useRef<string | null>(initialConversationId);\n /**\n * Transcript to feed the agent on its next prompt.\n *\n * A chat can outlive the agent that produced it: the transcript is durable,\n * the sandbox session is not. Showing the messages while the agent silently\n * remembers nothing is the worst of both worlds — ask it to \"add a widget to\n * that dashboard\" and it has no idea what \"that\" is. So when a chat is\n * resumed after its agent is gone, replay the conversation into its first\n * prompt.\n */\n const replayRef = useRef<string | null>(null);\n\n const persistSandboxId = useCallback((id: string | null) => {\n sandboxIdRef.current = id;\n writeStoredId(SANDBOX_ID_KEY, id);\n }, []);\n\n const persistSessionId = useCallback((id: string | null) => {\n sessionIdRef.current = id;\n writeStoredId(SESSION_ID_KEY, id);\n }, []);\n\n const persistConversationId = useCallback((id: string | null) => {\n conversationIdRef.current = id;\n writeStoredId(CONVERSATION_ID_KEY, id);\n }, []);\n\n const ensureRuntime = useCallback(\n async (\n workspaceId: string,\n authContext: AssistantSandboxAuthContext\n ): Promise<{ sandboxId: string; sessionId: string }> => {\n let sandboxId = sandboxIdRef.current;\n console.log('[BigConsole-Assistant] ensureRuntime start', { sandboxId, workspaceId });\n if (!sandboxId) {\n if (!getAccessToken()) {\n throw new Error('The assistant requires an authenticated session. Please sign in again.');\n }\n console.log('[BigConsole-Assistant] findExistingSandbox called');\n sandboxId = await findExistingSandbox(workspaceId, MODE, authContext);\n console.log('[BigConsole-Assistant] findExistingSandbox result', { sandboxId });\n\n if (sandboxId) {\n try {\n console.log('[BigConsole-Assistant] waitForSandboxReady called (reused)', { sandboxId });\n await waitForSandboxReady(sandboxId, workspaceId, authContext);\n console.log('[BigConsole-Assistant] waitForSandboxReady done (reused)', { sandboxId });\n console.log('[BigConsole-Assistant] waitForAssistantServiceReady called (reused)', { sandboxId });\n await waitForAssistantServiceReady(sandboxId, workspaceId, MODE, authContext);\n console.log('[BigConsole-Assistant] waitForAssistantServiceReady done (reused)', { sandboxId });\n } catch (error) {\n console.warn('[BigConsole-Assistant] existing sandbox unusable, falling back to fresh sandbox', {\n sandboxId,\n error: error instanceof Error ? error.message : String(error),\n });\n sandboxId = null;\n }\n }\n\n if (!sandboxId) {\n console.log('[BigConsole-Assistant] createAssistantSandbox called');\n sandboxId = await createAssistantSandbox(MODE, workspaceId, authContext);\n console.log('[BigConsole-Assistant] createAssistantSandbox result', { sandboxId });\n console.log('[BigConsole-Assistant] waitForSandboxReady called (fresh)', { sandboxId });\n await waitForSandboxReady(sandboxId, workspaceId, authContext);\n console.log('[BigConsole-Assistant] waitForSandboxReady done (fresh)', { sandboxId });\n console.log('[BigConsole-Assistant] waitForAssistantServiceReady called (fresh)', { sandboxId });\n await waitForAssistantServiceReady(sandboxId, workspaceId, MODE, authContext);\n console.log('[BigConsole-Assistant] waitForAssistantServiceReady done (fresh)', { sandboxId });\n }\n\n persistSandboxId(sandboxId);\n }\n\n let sessionId = sessionIdRef.current;\n console.log('[BigConsole-Assistant] session check', { sessionId, sandboxId });\n if (!sessionId) {\n console.log('[BigConsole-Assistant] createAssistantSession called', { sandboxId, workspaceId });\n const result = await createAssistantSession(sandboxId, workspaceId, MODE, authContext);\n sessionId = result.sessionId;\n persistSessionId(sessionId);\n }\n\n return { sandboxId, sessionId };\n },\n [getAccessToken]\n );\n\n const sendPrompt = useCallback(\n async ({\n prompt,\n attachments,\n onProgress,\n signal,\n }: AssistantSendArgs): Promise<{\n text: string;\n }> => {\n const workspaceId = getWorkspaceId(ctxWorkspaceId);\n console.log('[BigConsole-Assistant] sendPrompt called', {\n promptLength: prompt.length,\n workspaceId,\n hasCtxWorkspaceId: !!ctxWorkspaceId,\n authContextKeys: {\n hasAccessToken: !!getAccessToken(),\n hasWorkspaceToken: !!getWorkspaceToken(),\n hasUserId: !!userId,\n },\n locationSearch: window.location.search,\n });\n if (!workspaceId) {\n throw new Error('The assistant needs an active workspace. Open a workspace and try again.');\n }\n const authContext: AssistantSandboxAuthContext = {\n accessToken: getAccessToken(),\n workspaceToken: getWorkspaceToken(),\n userId,\n organizationId: getOrganizationId(),\n };\n console.log('[BigConsole-Assistant] authContext prepared', {\n hasAccessToken: !!authContext.accessToken,\n hasWorkspaceToken: !!authContext.workspaceToken,\n hasUserId: !!authContext.userId,\n hasOrgId: !!authContext.organizationId,\n });\n\n // Drive the live preview panel. The agent has no event stream, so the\n // narration IS the signal: the store parses it into a DataSink → Dashboard\n // → Parser → Widget rail. Fed here rather than in the widget because the\n // host owns this transport, so no fe-libs change is needed.\n const runStore = useAssistantRunStore.getState();\n runStore.startRun(prompt);\n const reportProgress = (partial: string): void => {\n onProgress(partial);\n useAssistantRunStore.getState().applyProgress(partial);\n };\n\n const run = async (attempt: 1 | 2): Promise<{ text: string }> => {\n try {\n console.log('[BigConsole-Assistant] run attempt', attempt);\n const { sandboxId, sessionId } = await ensureRuntime(workspaceId, authContext);\n console.log('[BigConsole-Assistant] ensureRuntime resolved', { sandboxId, sessionId });\n\n // Resuming a chat whose agent session is gone: hand the agent the\n // earlier transcript once, on the first prompt of the resumed chat, so\n // it answers with that context instead of from a blank slate. Consumed\n // on success — never replayed twice into the same session.\n const replay = replayRef.current;\n // Extract any uploaded files (JSON/CSV/Excel/PDF) into a capped text\n // block and fold it into the prompt the agent sees, so it can design a\n // DataSink straight from the pasted rows. The user-facing `prompt`\n // (preview narration, logs) stays clean.\n const attachmentBlock = attachments && attachments.length > 0 ? await buildAttachmentBlock(attachments) : '';\n const promptWithData = attachmentBlock ? `${prompt}\\n\\n${attachmentBlock}` : prompt;\n const agentPrompt = replay ? `${replay}\\n\\n---\\n\\n${promptWithData}` : promptWithData;\n\n const startedAt = Date.now();\n console.log('[BigConsole-Assistant] calling sendAssistantPromptAsync', {\n sandboxId,\n workspaceId,\n sessionId,\n promptLength: agentPrompt.length,\n replayed: Boolean(replay),\n });\n await sendAssistantPromptAsync(\n sandboxId,\n workspaceId,\n sessionId,\n agentPrompt,\n MODE,\n gatherPageContext(),\n authContext\n );\n\n const timeoutAt = Date.now() + STREAM_BUDGET_MS;\n let lastTtlExtensionAt = Date.now();\n let lastContent = '';\n let lastContentChangeAt = Date.now();\n let progress = buildProgress([], startedAt);\n\n while (Date.now() < timeoutAt) {\n if (signal.aborted) throw new Error('Cancelled');\n\n const messages = await getAssistantMessages(sandboxId, workspaceId, sessionId, authContext, 50);\n console.log('[BigConsole-Assistant] poll', {\n elapsedMs: Date.now() - startedAt,\n messageCount: messages.length,\n firstFewRoles: messages.slice(0, 3).map((m) => getMessageRole(m)),\n firstFewTimestamps: messages.slice(0, 3).map((m) => getRawMessageCreatedAt(m)),\n });\n progress = buildProgress(messages, startedAt, lastContent, lastContentChangeAt);\n console.log('[BigConsole-Assistant] progress', {\n contentPreview: progress.content.slice(0, 100),\n done: progress.done,\n lastContentChangeAt: Date.now() - lastContentChangeAt,\n });\n if (progress.content !== lastContent) {\n lastContent = progress.content;\n lastContentChangeAt = Date.now();\n }\n reportProgress(sanitize(progress.content));\n if (progress.done) {\n console.log('[BigConsole-Assistant] progress.done=true, breaking poll loop');\n break;\n }\n\n if (Date.now() - lastTtlExtensionAt > TTL_EXTEND_INTERVAL_MS) {\n await extendAssistantSandboxTTL(sandboxId, workspaceId, 600, authContext).catch(() => undefined);\n lastTtlExtensionAt = Date.now();\n }\n\n await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));\n }\n\n if (!progress.done) {\n // Do NOT say \"please try again\". We stopped watching; the agent did\n // not stop working, and anything it already created is real. Telling\n // people to retry is how you get duplicate dashboards.\n throw new Error(\n 'I stopped waiting for a reply, but I may still be working — anything I already created will be there. Check your dashboards and data sinks before asking again, so you do not end up with duplicates.'\n );\n }\n\n const reply = sanitize(progress.content);\n\n // An empty reply is a FAILED turn, not a successful one.\n //\n // `buildProgress` gives up and reports `done` when the agent has said\n // nothing for 15s, which is what happens when the runtime cannot serve\n // the turn at all (e.g. the sandbox quota is exhausted). Returning that\n // as a success showed the user a blank assistant bubble and — once\n // history became durable — wrote an empty transcript into it, leaving\n // a titled chat with nothing inside. Fail loudly and save nothing.\n if (!reply.trim()) {\n throw new Error(\n 'I could not produce a reply — the assistant runtime did not respond. It may be out of capacity right now. Nothing was changed; please try again shortly.'\n );\n }\n\n replayRef.current = null;\n\n // Persist the completed turn. Failing to save must not fail the turn —\n // the user got their answer, and the work the agent did is already real.\n try {\n const conversation = await saveAssistantTurn(\n {\n conversationId: conversationIdRef.current,\n prompt,\n reply,\n agentSessionId: sessionId,\n },\n workspaceId,\n authContext\n );\n persistConversationId(conversation.id);\n } catch (error) {\n console.warn('[BigConsole-Assistant] could not save turn to history', {\n error: error instanceof Error ? error.message : String(error),\n });\n }\n\n return { text: reply };\n } catch (error) {\n console.error('[BigConsole-Assistant] run error', {\n attempt,\n error: error instanceof Error ? error.message : String(error),\n stack: error instanceof Error ? error.stack : undefined,\n sandboxId: sandboxIdRef.current,\n sessionId: sessionIdRef.current,\n });\n // A stale/expired sandbox or session is recoverable — drop the warm\n // refs and retry once from a clean runtime.\n if (attempt === 1 && isRecoverable(error)) {\n persistSandboxId(null);\n persistSessionId(null);\n return run(2);\n }\n throw error;\n }\n };\n\n try {\n const result = await run(1);\n useAssistantRunStore.getState().finishRun(null);\n return result;\n } catch (error) {\n useAssistantRunStore.getState().finishRun(error instanceof Error ? error.message : String(error));\n throw error;\n }\n },\n [\n ctxWorkspaceId,\n ensureRuntime,\n getAccessToken,\n getWorkspaceToken,\n userId,\n persistSandboxId,\n persistSessionId,\n persistConversationId,\n ]\n );\n\n // ── Durable history (wspace-conversations) ───────────────────────────────\n //\n // The agent's own session lives in a sandbox with a 10-minute TTL and no\n // persistent volume, so it CANNOT be the store of record for a transcript the\n // user expects to keep. Every completed turn is written to wspace-conversations\n // instead, tagged with the product, so history is durable AND product-scoped —\n // a BigConsole chat can never surface in another product's panel.\n //\n // Two ids, doing different jobs:\n // conversationId — the durable chat. What History lists, and what the widget\n // treats as \"the session\".\n // sessionId — the LIVE agent session inside the sandbox. Ephemeral; a\n // hint stored on the conversation so a still-warm agent can\n // be resumed.\n\n const authFor = useCallback(\n (): AssistantSandboxAuthContext => ({\n accessToken: getAccessToken(),\n workspaceToken: getWorkspaceToken(),\n userId,\n organizationId: getOrganizationId(),\n }),\n [getAccessToken, getWorkspaceToken, userId]\n );\n\n const buildReplay = useCallback((messages: AssistantHistoryMessage[]): string | null => {\n if (messages.length === 0) return null;\n const transcript = messages\n .map((message) => `${message.role === 'user' ? 'User' : 'Assistant'}: ${message.content}`)\n .join('\\n\\n')\n .slice(-REPLAY_MAX_CHARS);\n\n return [\n 'You are resuming an earlier conversation. What follows is what was said in it — treat it as your own memory and continue seamlessly. Do not mention this replay, and do not redo work that was already completed.',\n '--- earlier in this conversation ---',\n transcript,\n '--- end ---',\n ].join('\\n\\n');\n }, []);\n\n const mapConversationMessages = useCallback(\n (messages: AssistantHistoryTurnMessage[]): AssistantHistoryMessage[] =>\n messages.map((message) => ({\n id: message.id,\n role: message.role === 'ASSISTANT' ? ('assistant' as const) : ('user' as const),\n content: sanitize(message.content),\n })),\n []\n );\n\n /**\n * Adopt a conversation: show its transcript, and line the agent up to continue\n * it — resuming the live session when one survives, replaying the transcript\n * when it does not.\n */\n const adoptConversation = useCallback(\n async (\n conversation: AssistantConversationSummary,\n workspaceId: string,\n auth: AssistantSandboxAuthContext\n ): Promise<AssistantHistoryMessage[]> => {\n const raw = await getAssistantConversationMessages(conversation.id, workspaceId, auth, HISTORY_MESSAGE_LIMIT);\n const messages = mapConversationMessages(raw);\n\n persistConversationId(conversation.id);\n\n if (conversation.agentSessionId) {\n // The agent may still be warm — adopt its session. If it has in fact\n // expired, sendPrompt's recoverable-retry path mints a fresh one.\n persistSessionId(conversation.agentSessionId);\n replayRef.current = null;\n } else {\n persistSessionId(null);\n replayRef.current = buildReplay(messages);\n }\n\n return messages;\n },\n [mapConversationMessages, persistConversationId, persistSessionId, buildReplay]\n );\n\n const loadHistory = useCallback(async (): Promise<AssistantHistoryMessage[]> => {\n const workspaceId = getWorkspaceId(ctxWorkspaceId);\n if (!workspaceId || !getAccessToken()) return [];\n const auth = authFor();\n\n try {\n const conversations = await listAssistantConversations(workspaceId, auth, SESSION_LIST_LIMIT);\n\n // Reopen the chat the user was in; failing that, their most recent one, so\n // a fresh login lands them back where they left off rather than in a blank\n // chat with their history hidden behind a menu.\n const current = conversationIdRef.current;\n const target = conversations.find((conversation) => conversation.id === current) ?? conversations[0];\n if (!target) return [];\n\n return await adoptConversation(target, workspaceId, auth);\n } catch (error) {\n console.warn('[BigConsole-Assistant] could not restore history', {\n error: error instanceof Error ? error.message : String(error),\n });\n return [];\n }\n }, [ctxWorkspaceId, getAccessToken, authFor, adoptConversation]);\n\n const listSessions = useCallback(async (): Promise<AssistantSessionSummaryLocal[]> => {\n const workspaceId = getWorkspaceId(ctxWorkspaceId);\n if (!workspaceId || !getAccessToken()) return [];\n\n try {\n const conversations = await listAssistantConversations(workspaceId, authFor(), SESSION_LIST_LIMIT);\n // Titles come from the store, so listing is ONE round-trip — no per-chat\n // probing, which is what used to make opening History feel slow.\n return conversations.map((conversation) => ({\n id: conversation.id,\n title: conversation.title?.trim() || 'New chat',\n updatedAt: Date.parse(conversation.updatedAt) || undefined,\n active: conversation.id === conversationIdRef.current,\n }));\n } catch {\n return [];\n }\n }, [ctxWorkspaceId, getAccessToken, authFor]);\n\n /**\n * Start a new chat — instantly, and with no backend call.\n *\n * Both ids are simply detached: the agent session is created lazily on the next\n * prompt, and the conversation row by the first saveAssistantTurn. Nothing to\n * wait for, and no empty conversations left behind for chats nobody used.\n */\n const newSession = useCallback(async (): Promise<void> => {\n persistConversationId(null);\n persistSessionId(null);\n replayRef.current = null;\n return Promise.resolve();\n }, [persistConversationId, persistSessionId]);\n\n const deleteSession = useCallback(\n async (conversationId: string): Promise<void> => {\n const workspaceId = getWorkspaceId(ctxWorkspaceId);\n if (!workspaceId) return;\n\n await deleteAssistantConversation(conversationId, workspaceId, authFor());\n\n // Deleting the chat you are looking at leaves you in a fresh one.\n if (conversationIdRef.current === conversationId) {\n persistConversationId(null);\n persistSessionId(null);\n replayRef.current = null;\n }\n },\n [ctxWorkspaceId, authFor, persistConversationId, persistSessionId]\n );\n\n const selectSession = useCallback(\n async (conversationId: string): Promise<AssistantHistoryMessage[]> => {\n const workspaceId = getWorkspaceId(ctxWorkspaceId);\n if (!workspaceId) return [];\n const auth = authFor();\n\n const conversations = await listAssistantConversations(workspaceId, auth, SESSION_LIST_LIMIT);\n const target = conversations.find((conversation) => conversation.id === conversationId);\n if (!target) return [];\n\n return adoptConversation(target, workspaceId, auth);\n },\n [ctxWorkspaceId, authFor, adoptConversation]\n );\n\n return useMemo<AssistantTransport>(\n () => ({ sendPrompt, loadHistory, listSessions, newSession, deleteSession, selectSession }),\n [sendPrompt, loadHistory, listSessions, newSession, deleteSession, selectSession]\n );\n}\n"],"mappings":";;;;;;;;AA8FA,IAAM,IAAsB,aAatB,KAAmB,MACnB,KAAmB,MACnB,KAAyB,KAIzB,IAAwB,KAExB,IAAqB,IAMrB,IAAmB,KAEnB,IAAiB,2BACjB,IAAiB,2BAEjB,IAAsB;AAE5B,SAAS,EAAa,GAA4B;AAChD,KAAI;AACF,SAAO,OAAO,eAAe,QAAQ,EAAI;SACnC;AAEN,SAAO;;;AAIX,SAAS,EAAc,GAAa,GAAyB;AAC3D,KAAI;AACF,EAAI,IAAI,OAAO,eAAe,QAAQ,GAAK,EAAG,GACzC,OAAO,eAAe,WAAW,EAAI;SACpC;;AAOV,SAAS,EAAuB,GAA+C;AAC7E,KAA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EACpB,OAAO,MAA0C;EAC/C,IAAM,IAAc,EAAe,EAAe;AAC7C,QAEL,MAAM,EAA4B,GAAgB,GAAa,GAAS,CAAC,EAGrE,EAAkB,YAAY,MAChC,EAAsB,KAAK,EAC3B,EAAiB,KAAK,EACtB,EAAU,UAAU;IAGxB;EAAC;EAAgB;EAAS;EAAuB;EAAiB,CACnE,EAEK,KAAgB,EACpB,OAAO,MAA+D;EACpE,IAAM,IAAc,EAAe,EAAe;AAClD,MAAI,CAAC,EAAa,QAAO,EAAE;EAC3B,IAAM,IAAO,GAAS,EAGhB,KADgB,MAAM,EAA2B,GAAa,GAAM,EAAmB,EAChE,MAAM,MAAiB,EAAa,OAAO,EAAe;AAGvF,SAFK,IAEE,EAAkB,GAAQ,GAAa,EAAK,GAF/B,EAAE;IAIxB;EAAC;EAAgB;EAAS;EAAkB,CAC7C;AAED,QAAO,SACE;EAAE;EAAY;EAAa;EAAc;EAAY;EAAe;EAAe,GAC1F;EAAC;EAAY;EAAa;EAAc;EAAY;EAAe;EAAc,CAClF"}
@@ -0,0 +1,25 @@
1
+ import { Component as e } from "react";
2
+ import { jsxs as t } from "react/jsx-runtime";
3
+ //#region src/bigconsole/components/embed/EmbedErrorBoundary.tsx
4
+ var n = class extends e {
5
+ state = { hasError: !1 };
6
+ static getDerivedStateFromError() {
7
+ return { hasError: !0 };
8
+ }
9
+ componentDidCatch(e, t) {}
10
+ render() {
11
+ return this.state.hasError ? /* @__PURE__ */ t("div", {
12
+ role: "alert",
13
+ className: "flex h-full w-full items-center justify-center bg-surface p-4 text-center text-sm text-secondary",
14
+ children: [
15
+ "This ",
16
+ this.props.label ?? "content",
17
+ " could not be displayed."
18
+ ]
19
+ }) : this.props.children;
20
+ }
21
+ };
22
+ //#endregion
23
+ export { n as EmbedErrorBoundary };
24
+
25
+ //# sourceMappingURL=EmbedErrorBoundary.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"EmbedErrorBoundary.js","names":[],"sources":["../../../../src/bigconsole/components/embed/EmbedErrorBoundary.tsx"],"sourcesContent":["/**\n * Customer-facing error boundary for embedded widgets/dashboards (BOFF-2986).\n *\n * Renders a neutral, safe message and NEVER surfaces internal details (stack\n * traces, ids, endpoints, config). One failing widget must not tear down the\n * whole dashboard, so this wraps each widget individually as well as the page.\n */\n\nimport { Component, type ErrorInfo, type ReactNode } from 'react';\n\ninterface Props {\n readonly children: ReactNode;\n /** Short, non-sensitive label for what failed (e.g. \"widget\"). */\n readonly label?: string;\n}\n\ninterface State {\n readonly hasError: boolean;\n}\n\nexport class EmbedErrorBoundary extends Component<Props, State> {\n state: State = { hasError: false };\n\n static getDerivedStateFromError(): State {\n return { hasError: true };\n }\n\n componentDidCatch(_error: Error, _info: ErrorInfo): void {\n // Intentionally no external reporting from the anonymous embed context — the\n // safe render below is the only user-visible outcome.\n }\n\n render(): ReactNode {\n if (this.state.hasError) {\n return (\n <div\n role=\"alert\"\n className=\"flex h-full w-full items-center justify-center bg-surface p-4 text-center text-sm text-secondary\"\n >\n This {this.props.label ?? 'content'} could not be displayed.\n </div>\n );\n }\n return this.props.children;\n }\n}\n"],"mappings":";;;AAoBA,IAAa,IAAb,cAAwC,EAAwB;CAC9D,QAAe,EAAE,UAAU,IAAO;CAElC,OAAO,2BAAkC;AACvC,SAAO,EAAE,UAAU,IAAM;;CAG3B,kBAAkB,GAAe,GAAwB;CAKzD,SAAoB;AAWlB,SAVI,KAAK,MAAM,WAEX,kBAAC,OAAD;GACE,MAAK;GACL,WAAU;aAFZ;IAGC;IACO,KAAK,MAAM,SAAS;IAAU;IAChC;OAGH,KAAK,MAAM"}
@@ -0,0 +1,36 @@
1
+ import { EMBED_WIDGET_COVERAGE as e } from "./renderer-manifest.js";
2
+ import { EmbedErrorBoundary as t } from "./EmbedErrorBoundary.js";
3
+ import { MetricCardEmbed as n } from "./widgets/MetricCardEmbed.js";
4
+ import { KpiComparisonEmbed as r } from "./widgets/KpiComparisonEmbed.js";
5
+ import { TableEmbed as i } from "./widgets/TableEmbed.js";
6
+ import { ListEmbed as a } from "./widgets/ListEmbed.js";
7
+ import { TextEmbed as o } from "./widgets/TextEmbed.js";
8
+ import { jsx as s } from "react/jsx-runtime";
9
+ //#region src/bigconsole/components/embed/EmbedWidgetRenderer.tsx
10
+ var c = {
11
+ metric_card: n,
12
+ kpi_card_comparison: r,
13
+ table: i,
14
+ list: a,
15
+ text: o
16
+ };
17
+ function l() {
18
+ return Object.keys(c);
19
+ }
20
+ function u({ title: e }) {
21
+ return /* @__PURE__ */ s("div", {
22
+ className: "flex h-full w-full items-center justify-center bg-surface p-4 text-center text-sm text-secondary",
23
+ children: e ? `“${e}” is not available in this embed.` : "This widget is not available in this embed."
24
+ });
25
+ }
26
+ function d(n) {
27
+ let { widget: r } = n, i = e[r.type]?.support === "implemented" ? c[r.type] : void 0;
28
+ return i ? /* @__PURE__ */ s(t, {
29
+ label: "widget",
30
+ children: /* @__PURE__ */ s(i, { ...n })
31
+ }) : /* @__PURE__ */ s(u, { title: r.title });
32
+ }
33
+ //#endregion
34
+ export { d as EmbedWidgetRenderer, l as getImplementedRendererTypes };
35
+
36
+ //# sourceMappingURL=EmbedWidgetRenderer.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"EmbedWidgetRenderer.js","names":[],"sources":["../../../../src/bigconsole/components/embed/EmbedWidgetRenderer.tsx"],"sourcesContent":["/**\n * Strict embed widget dispatcher (BOFF-2986).\n *\n * Maps a sanitized widget DTO to its embed renderer via an EXACT registry.\n * There is NO silent fallback (unlike the authenticated WidgetRendererFactory):\n * a type that is not `implemented` in the coverage manifest renders a neutral\n * \"not available\" placeholder, never a guessed or partial widget. Each widget is\n * wrapped in its own error boundary so one failure can't take down the page.\n */\n\nimport type { ComponentType } from 'react';\nimport type { WidgetType } from '../../types';\nimport type { EmbedWidgetRenderProps } from './types';\nimport { EMBED_WIDGET_COVERAGE } from './renderer-manifest';\nimport { EmbedErrorBoundary } from './EmbedErrorBoundary';\nimport { MetricCardEmbed } from './widgets/MetricCardEmbed';\nimport { KpiComparisonEmbed } from './widgets/KpiComparisonEmbed';\nimport { TableEmbed } from './widgets/TableEmbed';\nimport { ListEmbed } from './widgets/ListEmbed';\nimport { TextEmbed } from './widgets/TextEmbed';\n\n/**\n * Registry of implemented renderers. Every key here MUST be marked\n * `implemented` in EMBED_WIDGET_COVERAGE, and vice-versa — the completeness test\n * asserts the two stay in lockstep, so a renderer can never be silently missing\n * for a type the manifest claims to support.\n */\nconst IMPLEMENTED_RENDERERS: Partial<Record<WidgetType, ComponentType<EmbedWidgetRenderProps>>> = {\n metric_card: MetricCardEmbed,\n kpi_card_comparison: KpiComparisonEmbed,\n table: TableEmbed,\n list: ListEmbed,\n text: TextEmbed,\n};\n\nexport function getImplementedRendererTypes(): WidgetType[] {\n return Object.keys(IMPLEMENTED_RENDERERS) as WidgetType[];\n}\n\nfunction UnavailableWidget({ title }: { title?: string }) {\n return (\n <div className=\"flex h-full w-full items-center justify-center bg-surface p-4 text-center text-sm text-secondary\">\n {title ? `“${title}” is not available in this embed.` : 'This widget is not available in this embed.'}\n </div>\n );\n}\n\nexport function EmbedWidgetRenderer(props: EmbedWidgetRenderProps) {\n const { widget } = props;\n const coverage = EMBED_WIDGET_COVERAGE[widget.type];\n const Renderer = coverage?.support === 'implemented' ? IMPLEMENTED_RENDERERS[widget.type] : undefined;\n\n if (!Renderer) {\n return <UnavailableWidget title={widget.title} />;\n }\n\n return (\n <EmbedErrorBoundary label=\"widget\">\n <Renderer {...props} />\n </EmbedErrorBoundary>\n );\n}\n"],"mappings":";;;;;;;;;AA2BA,IAAM,IAA4F;CAChG,aAAa;CACb,qBAAqB;CACrB,OAAO;CACP,MAAM;CACN,MAAM;CACP;AAED,SAAgB,IAA4C;AAC1D,QAAO,OAAO,KAAK,EAAsB;;AAG3C,SAAS,EAAkB,EAAE,YAA6B;AACxD,QACE,kBAAC,OAAD;EAAK,WAAU;YACZ,IAAQ,IAAI,EAAM,qCAAqC;EACpD,CAAA;;AAIV,SAAgB,EAAoB,GAA+B;CACjE,IAAM,EAAE,cAAW,GAEb,IADW,EAAsB,EAAO,OACnB,YAAY,gBAAgB,EAAsB,EAAO,QAAQ,KAAA;AAM5F,QAJK,IAKH,kBAAC,GAAD;EAAoB,OAAM;YACxB,kBAAC,GAAD,EAAU,GAAI,GAAS,CAAA;EACJ,CAAA,GANd,kBAAC,GAAD,EAAmB,OAAO,EAAO,OAAS,CAAA"}
@@ -0,0 +1,62 @@
1
+ import { EmbedErrorBoundary as e } from "./EmbedErrorBoundary.js";
2
+ import { EmbedWidgetRenderer as t } from "./EmbedWidgetRenderer.js";
3
+ import { useState as n } from "react";
4
+ import { jsx as r, jsxs as i } from "react/jsx-runtime";
5
+ //#region src/bigconsole/components/embed/ReadOnlyDashboardRenderer.tsx
6
+ var a = 12;
7
+ function o({ page: e, capabilities: n }) {
8
+ return e.widgets.length === 0 ? /* @__PURE__ */ r("div", {
9
+ className: "flex h-40 items-center justify-center text-sm text-secondary",
10
+ children: "This page has no widgets."
11
+ }) : /* @__PURE__ */ r("div", {
12
+ className: "grid w-full gap-3 p-3",
13
+ style: {
14
+ gridTemplateColumns: `repeat(${a}, minmax(0, 1fr))`,
15
+ gridAutoRows: "minmax(80px, auto)"
16
+ },
17
+ children: e.widgets.map((e) => /* @__PURE__ */ r("div", {
18
+ className: "overflow-hidden rounded border border-border-default",
19
+ style: {
20
+ gridColumn: `${Math.min(Math.max(e.layout.x, 0), a - 1) + 1} / span ${Math.min(Math.max(e.layout.w, 1), a)}`,
21
+ gridRow: `${Math.max(e.layout.y, 0) + 1} / span ${Math.max(e.layout.h, 1)}`
22
+ },
23
+ children: /* @__PURE__ */ r(t, {
24
+ widget: e,
25
+ capabilities: n
26
+ })
27
+ }, e.id))
28
+ });
29
+ }
30
+ function s({ model: t }) {
31
+ let [a, s] = n(0), c = t.pages, l = c[Math.min(a, c.length - 1)];
32
+ return l ? /* @__PURE__ */ r(e, {
33
+ label: "dashboard",
34
+ children: /* @__PURE__ */ i("div", {
35
+ className: "flex h-full w-full flex-col bg-surface",
36
+ children: [c.length > 1 && /* @__PURE__ */ r("div", {
37
+ role: "tablist",
38
+ className: "flex gap-1 border-b border-border-default px-2",
39
+ children: c.map((e, t) => /* @__PURE__ */ r("button", {
40
+ role: "tab",
41
+ "aria-selected": t === a,
42
+ onClick: () => s(t),
43
+ className: t === a ? "border-b-2 border-primary px-3 py-2 text-sm text-primary" : "px-3 py-2 text-sm text-secondary",
44
+ children: e.title ?? `Page ${t + 1}`
45
+ }, e.id))
46
+ }), /* @__PURE__ */ r("div", {
47
+ className: "min-h-0 flex-1 overflow-auto",
48
+ children: /* @__PURE__ */ r(o, {
49
+ page: l,
50
+ capabilities: t.capabilities
51
+ })
52
+ })]
53
+ })
54
+ }) : /* @__PURE__ */ r("div", {
55
+ className: "flex h-full items-center justify-center bg-surface text-sm text-secondary",
56
+ children: "This dashboard has no pages."
57
+ });
58
+ }
59
+ //#endregion
60
+ export { s as ReadOnlyDashboardRenderer };
61
+
62
+ //# sourceMappingURL=ReadOnlyDashboardRenderer.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ReadOnlyDashboardRenderer.js","names":[],"sources":["../../../../src/bigconsole/components/embed/ReadOnlyDashboardRenderer.tsx"],"sourcesContent":["/**\n * Read-only embedded dashboard renderer (BOFF-2986).\n *\n * Renders the sanitized render model's pages + widgets on a simple responsive\n * grid. It is STRICTLY view-only: no builder toolbar, edit toggle, sharing,\n * save, palette, inspector or comments — those authenticated affordances do not\n * exist in this component tree at all.\n */\n\nimport { useState } from 'react';\nimport type { EmbedCapabilities, EmbedPageModel, EmbedRenderModel } from './types';\nimport { EmbedWidgetRenderer } from './EmbedWidgetRenderer';\nimport { EmbedErrorBoundary } from './EmbedErrorBoundary';\n\nconst GRID_COLUMNS = 12;\n\ninterface Props {\n readonly model: EmbedRenderModel;\n}\n\nfunction PageGrid({ page, capabilities }: { page: EmbedPageModel; capabilities: EmbedCapabilities }) {\n if (page.widgets.length === 0) {\n return (\n <div className=\"flex h-40 items-center justify-center text-sm text-secondary\">This page has no widgets.</div>\n );\n }\n return (\n <div\n className=\"grid w-full gap-3 p-3\"\n style={{ gridTemplateColumns: `repeat(${GRID_COLUMNS}, minmax(0, 1fr))`, gridAutoRows: 'minmax(80px, auto)' }}\n >\n {page.widgets.map((widget) => (\n <div\n key={widget.id}\n className=\"overflow-hidden rounded border border-border-default\"\n style={{\n // Clamp both ends: negative/oversized coordinates from malformed\n // model data must never produce an invalid CSS grid line.\n gridColumn: `${Math.min(Math.max(widget.layout.x, 0), GRID_COLUMNS - 1) + 1} / span ${Math.min(\n Math.max(widget.layout.w, 1),\n GRID_COLUMNS\n )}`,\n gridRow: `${Math.max(widget.layout.y, 0) + 1} / span ${Math.max(widget.layout.h, 1)}`,\n }}\n >\n <EmbedWidgetRenderer widget={widget} capabilities={capabilities} />\n </div>\n ))}\n </div>\n );\n}\n\nexport function ReadOnlyDashboardRenderer({ model }: Props) {\n const [activePageIndex, setActivePageIndex] = useState(0);\n const pages = model.pages;\n const activePage = pages[Math.min(activePageIndex, pages.length - 1)];\n\n if (!activePage) {\n return (\n <div className=\"flex h-full items-center justify-center bg-surface text-sm text-secondary\">\n This dashboard has no pages.\n </div>\n );\n }\n\n return (\n <EmbedErrorBoundary label=\"dashboard\">\n <div className=\"flex h-full w-full flex-col bg-surface\">\n {pages.length > 1 && (\n <div role=\"tablist\" className=\"flex gap-1 border-b border-border-default px-2\">\n {pages.map((page, i) => (\n <button\n key={page.id}\n role=\"tab\"\n aria-selected={i === activePageIndex}\n onClick={() => setActivePageIndex(i)}\n className={\n i === activePageIndex\n ? 'border-b-2 border-primary px-3 py-2 text-sm text-primary'\n : 'px-3 py-2 text-sm text-secondary'\n }\n >\n {page.title ?? `Page ${i + 1}`}\n </button>\n ))}\n </div>\n )}\n <div className=\"min-h-0 flex-1 overflow-auto\">\n <PageGrid page={activePage} capabilities={model.capabilities} />\n </div>\n </div>\n </EmbedErrorBoundary>\n );\n}\n"],"mappings":";;;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;KAAgB,CAAA;IAC5D,CAAA,CACF;;EACa,CAAA,GAhCnB,kBAAC,OAAD;EAAK,WAAU;YAA4E;EAErF,CAAA"}
@@ -0,0 +1,7 @@
1
+ import { EMBED_RENDER_MODEL_VERSION as e } from "./types.js";
2
+ import { EMBED_RENDERER_MANIFEST as t, EMBED_WIDGET_COVERAGE as n, isWidgetTypeEmbeddable as r } from "./renderer-manifest.js";
3
+ import { EmbedErrorBoundary as i } from "./EmbedErrorBoundary.js";
4
+ import { EmbedWidgetRenderer as a, getImplementedRendererTypes as o } from "./EmbedWidgetRenderer.js";
5
+ import { ReadOnlyDashboardRenderer as s } from "./ReadOnlyDashboardRenderer.js";
6
+ import { validateEmbedRenderModel as c } from "./validate.js";
7
+ export { t as EMBED_RENDERER_MANIFEST, e as EMBED_RENDER_MODEL_VERSION, n as EMBED_WIDGET_COVERAGE, i as EmbedErrorBoundary, a as EmbedWidgetRenderer, s as ReadOnlyDashboardRenderer, o as getImplementedRendererTypes, r as isWidgetTypeEmbeddable, c as validateEmbedRenderModel };
@@ -0,0 +1,77 @@
1
+ import "./types.js";
2
+ //#region src/bigconsole/components/embed/renderer-manifest.ts
3
+ var e = {
4
+ metric_card: { support: "implemented" },
5
+ kpi_card_comparison: { support: "implemented" },
6
+ table: { support: "implemented" },
7
+ list: { support: "implemented" },
8
+ text: { support: "implemented" },
9
+ chart: {
10
+ support: "blocked",
11
+ reason: "chart renderer + series schema pending"
12
+ },
13
+ funnel_chart: {
14
+ support: "blocked",
15
+ reason: "funnel renderer pending"
16
+ },
17
+ pivot_table: {
18
+ support: "blocked",
19
+ reason: "pivot projection schema pending"
20
+ },
21
+ gauge: {
22
+ support: "blocked",
23
+ reason: "gauge renderer pending"
24
+ },
25
+ progress: {
26
+ support: "blocked",
27
+ reason: "progress renderer pending"
28
+ },
29
+ form: {
30
+ support: "blocked",
31
+ reason: "requires side-effect action broker (post read-only MVP)"
32
+ },
33
+ iframe: {
34
+ support: "blocked",
35
+ reason: "requires frozen exact-origin sandbox declaration"
36
+ },
37
+ map: {
38
+ support: "blocked",
39
+ reason: "requires frozen map-provider origins"
40
+ },
41
+ heatmap: {
42
+ support: "blocked",
43
+ reason: "heatmap renderer pending"
44
+ },
45
+ calendar: {
46
+ support: "blocked",
47
+ reason: "calendar renderer pending"
48
+ },
49
+ kanban: {
50
+ support: "blocked",
51
+ reason: "kanban renderer pending"
52
+ },
53
+ timeline: {
54
+ support: "blocked",
55
+ reason: "timeline renderer pending"
56
+ },
57
+ retention: {
58
+ support: "blocked",
59
+ reason: "retention/cohort renderer pending"
60
+ },
61
+ custom: {
62
+ support: "blocked",
63
+ reason: "requires nested opaque-origin sandbox + signed manifest"
64
+ }
65
+ };
66
+ function t(t) {
67
+ return e[t]?.support === "implemented";
68
+ }
69
+ var n = {
70
+ renderModelVersion: 1,
71
+ implemented: Object.entries(e).filter(([, e]) => e.support === "implemented").map(([e]) => e).sort(),
72
+ blocked: Object.entries(e).filter(([, e]) => e.support === "blocked").map(([e]) => e).sort()
73
+ };
74
+ //#endregion
75
+ export { n as EMBED_RENDERER_MANIFEST, e as EMBED_WIDGET_COVERAGE, t as isWidgetTypeEmbeddable };
76
+
77
+ //# sourceMappingURL=renderer-manifest.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"renderer-manifest.js","names":[],"sources":["../../../../src/bigconsole/components/embed/renderer-manifest.ts"],"sourcesContent":["/**\n * Embed widget coverage manifest (BOFF-2986).\n *\n * A COMPLETE, explicit decision for every persisted widget type. There is no\n * silent fallback: a type is either `implemented` (has a sanitizer + embed\n * renderer + test) or `blocked` (publication containing it is rejected, and the\n * runtime renders a safe placeholder — never a wrong or partial widget).\n *\n * The completeness test (`renderer-manifest.test.ts`) enumerates the\n * `WidgetType` union and fails the build if any type is missing from this map,\n * so a newly-added widget type cannot ship without an explicit embed decision.\n */\n\nimport type { WidgetType } from '../../types';\nimport { EMBED_RENDER_MODEL_VERSION } from './types';\n\nexport type EmbedWidgetSupport = 'implemented' | 'blocked';\n\nexport interface EmbedWidgetCoverage {\n readonly support: EmbedWidgetSupport;\n /** Why a type is blocked (surfaced to publication validation + operators). */\n readonly reason?: string;\n}\n\n/**\n * Every `WidgetType` MUST appear here. Implemented set is the read-only MVP\n * native-data core; the rest are blocked with a concrete reason until their\n * sanitizer + renderer + tests land (each will flip to `implemented` in a\n * follow-up within this same renderer PR).\n */\nexport const EMBED_WIDGET_COVERAGE: Record<WidgetType, EmbedWidgetCoverage> = {\n // --- implemented (native data, no external fetch, no sandbox) ---\n metric_card: { support: 'implemented' },\n kpi_card_comparison: { support: 'implemented' },\n table: { support: 'implemented' },\n list: { support: 'implemented' },\n text: { support: 'implemented' },\n\n // --- blocked (pending sanitizer/renderer/tests in this PR) ---\n chart: { support: 'blocked', reason: 'chart renderer + series schema pending' },\n funnel_chart: { support: 'blocked', reason: 'funnel renderer pending' },\n pivot_table: { support: 'blocked', reason: 'pivot projection schema pending' },\n gauge: { support: 'blocked', reason: 'gauge renderer pending' },\n progress: { support: 'blocked', reason: 'progress renderer pending' },\n form: { support: 'blocked', reason: 'requires side-effect action broker (post read-only MVP)' },\n iframe: { support: 'blocked', reason: 'requires frozen exact-origin sandbox declaration' },\n map: { support: 'blocked', reason: 'requires frozen map-provider origins' },\n heatmap: { support: 'blocked', reason: 'heatmap renderer pending' },\n calendar: { support: 'blocked', reason: 'calendar renderer pending' },\n kanban: { support: 'blocked', reason: 'kanban renderer pending' },\n timeline: { support: 'blocked', reason: 'timeline renderer pending' },\n retention: { support: 'blocked', reason: 'retention/cohort renderer pending' },\n custom: { support: 'blocked', reason: 'requires nested opaque-origin sandbox + signed manifest' },\n};\n\nexport function isWidgetTypeEmbeddable(type: WidgetType): boolean {\n return EMBED_WIDGET_COVERAGE[type]?.support === 'implemented';\n}\n\n/** Immutable manifest emitted alongside the asset bundle for contract auditing. */\nexport const EMBED_RENDERER_MANIFEST = {\n renderModelVersion: EMBED_RENDER_MODEL_VERSION,\n implemented: Object.entries(EMBED_WIDGET_COVERAGE)\n .filter(([, v]) => v.support === 'implemented')\n .map(([k]) => k)\n .sort(),\n blocked: Object.entries(EMBED_WIDGET_COVERAGE)\n .filter(([, v]) => v.support === 'blocked')\n .map(([k]) => k)\n .sort(),\n} as const;\n"],"mappings":";;AA8BA,IAAa,IAAiE;CAE5E,aAAa,EAAE,SAAS,eAAe;CACvC,qBAAqB,EAAE,SAAS,eAAe;CAC/C,OAAO,EAAE,SAAS,eAAe;CACjC,MAAM,EAAE,SAAS,eAAe;CAChC,MAAM,EAAE,SAAS,eAAe;CAGhC,OAAO;EAAE,SAAS;EAAW,QAAQ;EAA0C;CAC/E,cAAc;EAAE,SAAS;EAAW,QAAQ;EAA2B;CACvE,aAAa;EAAE,SAAS;EAAW,QAAQ;EAAmC;CAC9E,OAAO;EAAE,SAAS;EAAW,QAAQ;EAA0B;CAC/D,UAAU;EAAE,SAAS;EAAW,QAAQ;EAA6B;CACrE,MAAM;EAAE,SAAS;EAAW,QAAQ;EAA2D;CAC/F,QAAQ;EAAE,SAAS;EAAW,QAAQ;EAAoD;CAC1F,KAAK;EAAE,SAAS;EAAW,QAAQ;EAAwC;CAC3E,SAAS;EAAE,SAAS;EAAW,QAAQ;EAA4B;CACnE,UAAU;EAAE,SAAS;EAAW,QAAQ;EAA6B;CACrE,QAAQ;EAAE,SAAS;EAAW,QAAQ;EAA2B;CACjE,UAAU;EAAE,SAAS;EAAW,QAAQ;EAA6B;CACrE,WAAW;EAAE,SAAS;EAAW,QAAQ;EAAqC;CAC9E,QAAQ;EAAE,SAAS;EAAW,QAAQ;EAA2D;CAClG;AAED,SAAgB,EAAuB,GAA2B;AAChE,QAAO,EAAsB,IAAO,YAAY;;AAIlD,IAAa,IAA0B;CACrC,oBAAA;CACA,aAAa,OAAO,QAAQ,EAAsB,CAC/C,QAAQ,GAAG,OAAO,EAAE,YAAY,cAAc,CAC9C,KAAK,CAAC,OAAO,EAAE,CACf,MAAM;CACT,SAAS,OAAO,QAAQ,EAAsB,CAC3C,QAAQ,GAAG,OAAO,EAAE,YAAY,UAAU,CAC1C,KAAK,CAAC,OAAO,EAAE,CACf,MAAM;CACV"}
@@ -0,0 +1,6 @@
1
+ //#region src/bigconsole/components/embed/types.ts
2
+ var e = 1;
3
+ //#endregion
4
+ export { e as EMBED_RENDER_MODEL_VERSION };
5
+
6
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","names":[],"sources":["../../../../src/bigconsole/components/embed/types.ts"],"sourcesContent":["/**\n * Stable, versioned embed render-model contract (BOFF-2986).\n *\n * This is the ONLY shape the read-only embed renderer consumes. It is a\n * sanitized DTO produced by the BigConsole publication builder — it deliberately\n * carries NO authenticated stores, Apollo clients, data-source configs,\n * credentials or internal ids. The renderer never fetches data itself; all\n * values are pre-projected into the model or fetched later through the\n * publication-scoped interaction controller using opaque aliases.\n *\n * Backend (publication builder) and frontend (renderer) MUST agree on\n * `EMBED_RENDER_MODEL_VERSION`. A mismatch fails closed at load time rather than\n * rendering a stale/incompatible view.\n */\n\nimport type { WidgetType } from '../../types';\n\n/** Bump on any breaking change to the DTO shapes below. */\nexport const EMBED_RENDER_MODEL_VERSION = 1 as const;\n\n/** Pure layout box (grid units); no store, no event emission. */\nexport interface EmbedWidgetLayout {\n readonly x: number;\n readonly y: number;\n readonly w: number;\n readonly h: number;\n}\n\n/**\n * A single widget as projected for embedding. `config` and `data` are already\n * sanitized and schema-narrowed per widget type by the publication builder; the\n * renderer validates them again against its per-type schema before rendering.\n */\nexport interface EmbedWidgetModel {\n /** Opaque, publication-scoped widget id (not the internal DB id). */\n readonly id: string;\n readonly type: WidgetType;\n readonly title?: string;\n readonly layout: EmbedWidgetLayout;\n /** Sanitized, type-narrowed presentation config. */\n readonly config: Readonly<Record<string, unknown>>;\n /** Sanitized, pre-projected data payload (or null for interaction-fetched). */\n readonly data: Readonly<Record<string, unknown>> | null;\n}\n\nexport interface EmbedPageModel {\n readonly id: string;\n readonly title?: string;\n readonly widgets: readonly EmbedWidgetModel[];\n}\n\n/**\n * Publication-approved runtime capabilities. Everything defaults OFF; the\n * renderer must never enable an interaction the publication did not grant.\n */\nexport interface EmbedCapabilities {\n readonly filters: boolean;\n readonly drilldown: boolean;\n readonly downloads: boolean;\n /** Side-effect actions (forms/webhooks/workflows) — out of scope for read-only MVP. */\n readonly actions: boolean;\n}\n\nexport interface EmbedRenderModel {\n readonly renderModelVersion: number;\n readonly clientContractVersion: number;\n readonly title?: string;\n readonly pages: readonly EmbedPageModel[];\n readonly capabilities: EmbedCapabilities;\n /** ISO timestamp the immutable publication was frozen. */\n readonly definitionPublishedAt: string;\n}\n\n/** Result of validating an inbound render model before rendering. */\nexport type EmbedModelValidation =\n { readonly ok: true; readonly model: EmbedRenderModel } | { readonly ok: false; readonly reason: string };\n\n/**\n * Shape every embed widget renderer component receives. It gets the sanitized\n * model plus a controller for publication-scoped interactions — never raw hooks.\n */\nexport interface EmbedWidgetRenderProps {\n readonly widget: EmbedWidgetModel;\n readonly capabilities: EmbedCapabilities;\n}\n"],"mappings":";AAkBA,IAAa,IAA6B"}
@@ -0,0 +1,29 @@
1
+ import "./types.js";
2
+ //#region src/bigconsole/components/embed/validate.ts
3
+ function e(e) {
4
+ if (!e || typeof e != "object") return {
5
+ ok: !1,
6
+ reason: "model is not an object"
7
+ };
8
+ let t = e;
9
+ if (t.renderModelVersion !== 1) return {
10
+ ok: !1,
11
+ reason: `unsupported renderModelVersion ${String(t.renderModelVersion)} (expected 1)`
12
+ };
13
+ if (!Array.isArray(t.pages)) return {
14
+ ok: !1,
15
+ reason: "pages missing or not an array"
16
+ };
17
+ let n = t.capabilities;
18
+ return !n || typeof n != "object" || Array.isArray(n) ? {
19
+ ok: !1,
20
+ reason: "capabilities missing or malformed"
21
+ } : {
22
+ ok: !0,
23
+ model: e
24
+ };
25
+ }
26
+ //#endregion
27
+ export { e as validateEmbedRenderModel };
28
+
29
+ //# sourceMappingURL=validate.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"validate.js","names":[],"sources":["../../../../src/bigconsole/components/embed/validate.ts"],"sourcesContent":["/**\n * Render-model validation (BOFF-2986).\n *\n * Fails closed: an inbound model with the wrong version or a structurally\n * invalid shape is rejected before rendering, rather than partially displayed.\n */\nimport { EMBED_RENDER_MODEL_VERSION, type EmbedModelValidation, type EmbedRenderModel } from './types';\n\nexport function validateEmbedRenderModel(input: unknown): EmbedModelValidation {\n if (!input || typeof input !== 'object') {\n return { ok: false, reason: 'model is not an object' };\n }\n const m = input as Record<string, unknown>;\n if (m.renderModelVersion !== EMBED_RENDER_MODEL_VERSION) {\n return {\n ok: false,\n reason: `unsupported renderModelVersion ${String(m.renderModelVersion)} (expected ${EMBED_RENDER_MODEL_VERSION})`,\n };\n }\n if (!Array.isArray(m.pages)) {\n return { ok: false, reason: 'pages missing or not an array' };\n }\n const caps = m.capabilities;\n // `typeof [] === 'object'`, so an array would slip through a bare object check\n // and then every `capabilities.<flag>` read as undefined (silently disabling\n // capabilities) — reject non-plain-object capabilities explicitly (fail closed).\n if (!caps || typeof caps !== 'object' || Array.isArray(caps)) {\n return { ok: false, reason: 'capabilities missing or malformed' };\n }\n // Structural shape is acceptable; per-widget config/data are re-narrowed at\n // render time by each renderer, so we don't deep-validate every widget here.\n return { ok: true, model: input as EmbedRenderModel };\n}\n"],"mappings":";;AAQA,SAAgB,EAAyB,GAAsC;AAC7E,KAAI,CAAC,KAAS,OAAO,KAAU,SAC7B,QAAO;EAAE,IAAI;EAAO,QAAQ;EAA0B;CAExD,IAAM,IAAI;AACV,KAAI,EAAE,uBAAA,EACJ,QAAO;EACL,IAAI;EACJ,QAAQ,kCAAkC,OAAO,EAAE,mBAAmB,CAAC;EACxE;AAEH,KAAI,CAAC,MAAM,QAAQ,EAAE,MAAM,CACzB,QAAO;EAAE,IAAI;EAAO,QAAQ;EAAiC;CAE/D,IAAM,IAAO,EAAE;AASf,QALI,CAAC,KAAQ,OAAO,KAAS,YAAY,MAAM,QAAQ,EAAK,GACnD;EAAE,IAAI;EAAO,QAAQ;EAAqC,GAI5D;EAAE,IAAI;EAAM,OAAO;EAA2B"}
@@ -0,0 +1,34 @@
1
+ import { asFiniteNumber as e, asRecord as t, asString as n, formatNumber as r } from "./shared.js";
2
+ import { jsx as i, jsxs as a } from "react/jsx-runtime";
3
+ //#region src/bigconsole/components/embed/widgets/KpiComparisonEmbed.tsx
4
+ function o({ widget: o }) {
5
+ let s = t(o.config), c = t(o.data), l = e(c.current ?? s.current), u = e(c.previous ?? s.previous), d = n(s.label ?? o.title, "KPI"), f = null;
6
+ l !== null && u !== null && u !== 0 && (f = (l - u) / Math.abs(u) * 100);
7
+ let p = f !== null && f >= 0;
8
+ return /* @__PURE__ */ a("div", {
9
+ className: "flex h-full w-full flex-col justify-center gap-1 bg-surface p-4",
10
+ children: [
11
+ /* @__PURE__ */ i("div", {
12
+ className: "text-xs uppercase tracking-wide text-secondary",
13
+ children: d
14
+ }),
15
+ /* @__PURE__ */ i("div", {
16
+ className: "text-3xl font-semibold text-primary",
17
+ children: l === null ? "—" : r(l, s)
18
+ }),
19
+ f !== null && /* @__PURE__ */ a("div", {
20
+ className: p ? "text-sm text-status-success-text" : "text-sm text-status-error-text",
21
+ children: [
22
+ p ? "▲" : "▼",
23
+ " ",
24
+ Math.abs(f).toFixed(1),
25
+ "%"
26
+ ]
27
+ })
28
+ ]
29
+ });
30
+ }
31
+ //#endregion
32
+ export { o as KpiComparisonEmbed };
33
+
34
+ //# sourceMappingURL=KpiComparisonEmbed.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"KpiComparisonEmbed.js","names":[],"sources":["../../../../../src/bigconsole/components/embed/widgets/KpiComparisonEmbed.tsx"],"sourcesContent":["/** Read-only KPI comparison embed renderer (BOFF-2986). */\nimport type { EmbedWidgetRenderProps } from '../types';\nimport { asRecord, asString, asFiniteNumber, formatNumber } from './shared';\n\nexport function KpiComparisonEmbed({ widget }: EmbedWidgetRenderProps) {\n const config = asRecord(widget.config);\n const data = asRecord(widget.data);\n const current = asFiniteNumber(data.current ?? config.current);\n const previous = asFiniteNumber(data.previous ?? config.previous);\n const label = asString(config.label ?? widget.title, 'KPI');\n\n let deltaPct: number | null = null;\n if (current !== null && previous !== null && previous !== 0) {\n deltaPct = ((current - previous) / Math.abs(previous)) * 100;\n }\n const positive = deltaPct !== null && deltaPct >= 0;\n\n return (\n <div className=\"flex h-full w-full flex-col justify-center gap-1 bg-surface p-4\">\n <div className=\"text-xs uppercase tracking-wide text-secondary\">{label}</div>\n <div className=\"text-3xl font-semibold text-primary\">\n {current !== null ? formatNumber(current, config) : '—'}\n </div>\n {deltaPct !== null && (\n <div className={positive ? 'text-sm text-status-success-text' : 'text-sm text-status-error-text'}>\n {positive ? '▲' : '▼'} {Math.abs(deltaPct).toFixed(1)}%\n </div>\n )}\n </div>\n );\n}\n"],"mappings":";;;AAIA,SAAgB,EAAmB,EAAE,aAAkC;CACrE,IAAM,IAAS,EAAS,EAAO,OAAO,EAChC,IAAO,EAAS,EAAO,KAAK,EAC5B,IAAU,EAAe,EAAK,WAAW,EAAO,QAAQ,EACxD,IAAW,EAAe,EAAK,YAAY,EAAO,SAAS,EAC3D,IAAQ,EAAS,EAAO,SAAS,EAAO,OAAO,MAAM,EAEvD,IAA0B;AAC9B,CAAI,MAAY,QAAQ,MAAa,QAAQ,MAAa,MACxD,KAAa,IAAU,KAAY,KAAK,IAAI,EAAS,GAAI;CAE3D,IAAM,IAAW,MAAa,QAAQ,KAAY;AAElD,QACE,kBAAC,OAAD;EAAK,WAAU;YAAf;GACE,kBAAC,OAAD;IAAK,WAAU;cAAkD;IAAY,CAAA;GAC7E,kBAAC,OAAD;IAAK,WAAU;cACZ,MAAY,OAAuC,MAAhC,EAAa,GAAS,EAAO;IAC7C,CAAA;GACL,MAAa,QACZ,kBAAC,OAAD;IAAK,WAAW,IAAW,qCAAqC;cAAhE;KACG,IAAW,MAAM;KAAI;KAAE,KAAK,IAAI,EAAS,CAAC,QAAQ,EAAE;KAAC;KAClD;;GAEJ"}