@burdenoff/microfe-bigconsole 2026.912.3 → 2026.915.1

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.
@@ -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 { 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 // No usable assistant content for THIS turn yet. Separate \"still thinking\"\n // from \"responded but unreadable\", so a slow reasoning model is never\n // mistaken for a dead runtime:\n //\n // - No assistant message exists AT ALL: the agent is still starting up, or\n // gpt-5.6-terra (a reasoning model) is still thinking before its first\n // token. Time-to-first-message routinely exceeds the old 15s window,\n // especially with a large system prompt — which declared the turn\n // done-and-empty and surfaced \"the assistant runtime did not respond\"\n // even though the backend was healthy. NEVER give up here; let the outer\n // turn budget (STREAM_BUDGET_MS) decide, exactly like the running-tool\n // guard in the branch below.\n //\n // - An assistant message exists but none maps to this turn (timestamp skew\n // / role mismatch): the turn may really be over but unreadable. Keep a\n // staleness fallback — but give reasoning models ample room (90s, not\n // 15s) so a slow first token is never read as a stalled turn.\n const anyAssistantMessage = messages.some((message) => getMessageRole(message) === 'assistant');\n const emptyForMs =\n previousContent === content && previousContentAtMs !== undefined ? Date.now() - previousContentAtMs : 0;\n // Skew case (a message exists but is unreadable): 90s is plenty.\n // Nothing-at-all case (slow reasoning first token): wait 150s before calling\n // it a genuine no-show — a safe upper bound for time-to-first-token that\n // still fails a truly dead runtime (unbooted sandbox / quota) in ~2.5 min\n // instead of the old 15s that tripped healthy reasoning turns.\n done = anyAssistantMessage ? emptyForMs >= 90_000 : emptyForMs >= 150_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 // An empty turn (\"the assistant runtime did not respond\") is most often a\n // stale/dead session or sandbox reference — a prompt to a session whose\n // sandbox has been recycled persists nothing rather than erroring. Treat it\n // as recoverable so the retry drops the warm refs and mints a fresh\n // sandbox+session; a genuinely down runtime simply empties again on attempt 2\n // and then surfaces to the user. (attempt-gated to a single retry upstream.)\n 'the assistant runtime did not respond',\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 // Do NOT adopt the stored agentSessionId. That session lives inside an\n // ephemeral sandbox (~600s TTL) and is almost always gone by the time a\n // past conversation is reopened — and a prompt to a dead session does not\n // error, it silently persists nothing, which surfaces as \"the assistant\n // runtime did not respond\". Always start a FRESH opencode session on the\n // current sandbox and replay the transcript so the agent keeps its context.\n // (A mass sandbox recycle — e.g. an image rollout — invalidates every\n // stored session at once, which is exactly when adoption bites hardest.)\n persistSessionId(null);\n replayRef.current = buildReplay(messages);\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,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,EAAI,CAChB,MAAQ,KAFN;SAGX;AACN,SAAO;;;AAIX,SAAS,EAAe,GAAiC;AAEvD,QADe,IAAI,gBAAgB,OAAO,SAAS,OAAO,CAC5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3B,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"}
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 isCachedAssistantSandboxReusable,\n sendAssistantPromptAsync,\n waitForAssistantServiceReady,\n waitForSandboxReady,\n} from './assistantApi';\nimport {\n ASSISTANT_SANDBOX_ID_KEY,\n ASSISTANT_SESSION_ID_KEY,\n type AssistantRuntimeApi,\n LEGACY_ASSISTANT_RUNTIME_KEYS,\n resolveAssistantRuntime,\n} from './assistantRuntime';\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\n/**\n * The durable chat. This is the identity History lists. Unversioned on purpose:\n * it names a product-scoped wspace-conversations row, not a sandbox, so it was\n * never subject to the cross-product adoption the runtime keys were.\n */\nconst CONVERSATION_ID_KEY = 'bc-assistant-conversation-id';\n\nconst RUNTIME_API: AssistantRuntimeApi = {\n isCachedAssistantSandboxReusable,\n findExistingSandbox,\n createAssistantSandbox,\n waitForSandboxReady,\n waitForAssistantServiceReady,\n createAssistantSession,\n};\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 // No usable assistant content for THIS turn yet. Separate \"still thinking\"\n // from \"responded but unreadable\", so a slow reasoning model is never\n // mistaken for a dead runtime:\n //\n // - No assistant message exists AT ALL: the agent is still starting up, or\n // gpt-5.6-terra (a reasoning model) is still thinking before its first\n // token. Time-to-first-message routinely exceeds the old 15s window,\n // especially with a large system prompt — which declared the turn\n // done-and-empty and surfaced \"the assistant runtime did not respond\"\n // even though the backend was healthy. NEVER give up here; let the outer\n // turn budget (STREAM_BUDGET_MS) decide, exactly like the running-tool\n // guard in the branch below.\n //\n // - An assistant message exists but none maps to this turn (timestamp skew\n // / role mismatch): the turn may really be over but unreadable. Keep a\n // staleness fallback — but give reasoning models ample room (90s, not\n // 15s) so a slow first token is never read as a stalled turn.\n const anyAssistantMessage = messages.some((message) => getMessageRole(message) === 'assistant');\n const emptyForMs =\n previousContent === content && previousContentAtMs !== undefined ? Date.now() - previousContentAtMs : 0;\n // Skew case (a message exists but is unreadable): 90s is plenty.\n // Nothing-at-all case (slow reasoning first token): wait 150s before calling\n // it a genuine no-show — a safe upper bound for time-to-first-token that\n // still fails a truly dead runtime (unbooted sandbox / quota) in ~2.5 min\n // instead of the old 15s that tripped healthy reasoning turns.\n done = anyAssistantMessage ? emptyForMs >= 90_000 : emptyForMs >= 150_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 // An empty turn (\"the assistant runtime did not respond\") is most often a\n // stale/dead session or sandbox reference — a prompt to a session whose\n // sandbox has been recycled persists nothing rather than erroring. Treat it\n // as recoverable so the retry drops the warm refs and mints a fresh\n // sandbox+session; a genuinely down runtime simply empties again on attempt 2\n // and then surfaces to the user. (attempt-gated to a single retry upstream.)\n 'the assistant runtime did not respond',\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 rehydrated sandbox id is NOT trusted as-is: before its\n // first use `resolveAssistantRuntime` re-fetches it and holds it to the reuse\n // predicate (product stamp, owner, confirmWrites, status), discarding it — and\n // its session — if it fails. A stale/expired sandbox is discarded the same way.\n const [initialSandboxId, initialSessionId, initialConversationId] = useMemo(() => {\n // Pre-BOFF-7331 builds wrote unversioned keys and may have cached another\n // product's sandbox in them. Never read them; clear them.\n for (const legacyKey of LEGACY_ASSISTANT_RUNTIME_KEYS) writeStoredId(legacyKey, null);\n return [\n readStoredId(ASSISTANT_SANDBOX_ID_KEY),\n readStoredId(ASSISTANT_SESSION_ID_KEY),\n readStoredId(CONVERSATION_ID_KEY),\n ] as const;\n }, []);\n\n const sandboxIdRef = useRef<string | null>(initialSandboxId);\n const sessionIdRef = useRef<string | null>(initialSessionId);\n const conversationIdRef = useRef<string | null>(initialConversationId);\n /** Memory only: which sandbox (for which user) this page lifecycle has proven drivable. */\n const verifiedSandboxKeyRef = useRef<string | null>(null);\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(ASSISTANT_SANDBOX_ID_KEY, id);\n }, []);\n\n const persistSessionId = useCallback((id: string | null) => {\n sessionIdRef.current = id;\n writeStoredId(ASSISTANT_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 resolveAssistantRuntime({\n workspaceId,\n mode: MODE,\n authContext,\n api: RUNTIME_API,\n hasAccessToken: () => !!getAccessToken(),\n store: {\n getSandboxId: () => sandboxIdRef.current,\n setSandboxId: persistSandboxId,\n getSessionId: () => sessionIdRef.current,\n setSessionId: persistSessionId,\n getVerifiedSandboxKey: () => verifiedSandboxKeyRef.current,\n setVerifiedSandboxKey: (key) => {\n verifiedSandboxKeyRef.current = key;\n },\n },\n }),\n [getAccessToken, persistSandboxId, persistSessionId]\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 // Do NOT adopt the stored agentSessionId. That session lives inside an\n // ephemeral sandbox (~600s TTL) and is almost always gone by the time a\n // past conversation is reopened — and a prompt to a dead session does not\n // error, it silently persists nothing, which surfaces as \"the assistant\n // runtime did not respond\". Always start a FRESH opencode session on the\n // current sandbox and replay the transcript so the agent keeps its context.\n // (A mass sandbox recycle — e.g. an image rollout — invalidates every\n // stored session at once, which is exactly when adoption bites hardest.)\n persistSessionId(null);\n replayRef.current = buildReplay(messages);\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":";;;;;;;;;AAsGA,IAAM,IAAsB,aAatB,KAAmB,MACnB,KAAmB,MACnB,KAAyB,KAIzB,IAAwB,KAExB,IAAqB,IAMrB,KAAmB,KAOnB,IAAsB,gCAEtB,KAAmC;CACvC;CACA;CACA;CACA;CACA;CACA;CACD;AAED,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,EAAI,CAChB,MAAQ,KAFN;SAGX;AACN,SAAO;;;AAIX,SAAS,EAAe,GAAiC;AAEvD,QADe,IAAI,gBAAgB,OAAO,SAAS,OAAO,CAC5C,IAAI,YAAY,IAAI,EAAuB,cAAc,IAAI,KAAY;;AAGzF,SAAS,IAA4B;AAEnC,QADe,IAAI,gBAAgB,OAAO,SAAS,OAAO,CAC5C,IAAI,MAAM,IAAI,EAAuB,iBAAiB;;AAKtE,SAAS,EAAe,GAAkD;AAExE,QAAO,EAAQ,MAAM,Q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AO,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"}
@@ -1,28 +1,28 @@
1
- import { useEffect as e, useState as t } from "react";
2
- import { jsx as n, jsxs as r } from "react/jsx-runtime";
1
+ import { useEffect as e, useLayoutEffect as t, useState as n } from "react";
2
+ import { jsx as r, jsxs as i } from "react/jsx-runtime";
3
3
  //#region src/bigconsole/components/preview/previewShared.tsx
4
- function i(e, t) {
4
+ function a(e, t) {
5
5
  return e < 5 ? t("bigconsole.widget.aiPreview.agoJustNow", "just now") : e < 60 ? t("bigconsole.widget.aiPreview.agoSeconds", "{{n}}s ago", { n: e }) : e < 3600 ? t("bigconsole.widget.aiPreview.agoMinutes", "{{n}}m ago", { n: Math.floor(e / 60) }) : t("bigconsole.widget.aiPreview.agoHours", "{{n}}h ago", { n: Math.floor(e / 3600) });
6
6
  }
7
- function a(n) {
8
- let [r, i] = t(0);
9
- return e(() => {
10
- if (!n) {
7
+ function o(e) {
8
+ let [r, i] = n(0);
9
+ return t(() => {
10
+ if (!e) {
11
11
  i(0);
12
12
  return;
13
13
  }
14
- let e = () => {
14
+ let t = () => {
15
15
  let e = document.querySelector("[data-testid=\"assistant-widget-window\"][data-layout=\"sidebar\"]")?.getBoundingClientRect(), t = e && e.width < window.innerWidth * .75 ? Math.round(e.width) : 0;
16
16
  i((e) => e === t ? e : t);
17
17
  };
18
- e();
19
- let t = window.setInterval(e, 500);
20
- return window.addEventListener("resize", e), () => {
21
- window.clearInterval(t), window.removeEventListener("resize", e);
18
+ t();
19
+ let n = window.setInterval(t, 500);
20
+ return window.addEventListener("resize", t), () => {
21
+ window.clearInterval(n), window.removeEventListener("resize", t);
22
22
  };
23
- }, [n]), r;
23
+ }, [e]), r;
24
24
  }
25
- var o = {
25
+ var s = {
26
26
  datasink: {
27
27
  key: "bigconsole.widget.aiPreview.tab.dataSink",
28
28
  fallback: "Data Sink"
@@ -40,7 +40,7 @@ var o = {
40
40
  fallback: "Widget"
41
41
  }
42
42
  };
43
- function s(e) {
43
+ function c(e) {
44
44
  let t = e("bigconsole.widget.aiPreview.buildProgress", "Build progress"), n = e("bigconsole.widget.aiPreview.stepSkipped", "skipped");
45
45
  return {
46
46
  errorHeading: e("bigconsole.widget.aiPreview.errorHeading", "Build stopped"),
@@ -56,8 +56,8 @@ function s(e) {
56
56
  }
57
57
  };
58
58
  }
59
- function c({ state: i, stateLabel: a, updatedLabel: o, updatedAt: s, ago: c }) {
60
- let [l, u] = t(() => Date.now());
59
+ function l({ state: t, stateLabel: a, updatedLabel: o, updatedAt: s, ago: c }) {
60
+ let [l, u] = n(() => Date.now());
61
61
  e(() => {
62
62
  if (s === null) return;
63
63
  u(Date.now());
@@ -65,17 +65,17 @@ function c({ state: i, stateLabel: a, updatedLabel: o, updatedAt: s, ago: c }) {
65
65
  return () => window.clearInterval(e);
66
66
  }, [s]);
67
67
  let d = s === null ? 0 : Math.max(0, Math.floor((l - s) / 1e3)), f = "inline-flex items-center gap-1.5 rounded-full px-2 py-0.5 text-[11px] font-semibold uppercase tracking-wide";
68
- return /* @__PURE__ */ r("span", {
68
+ return /* @__PURE__ */ i("span", {
69
69
  className: "inline-flex items-center gap-2",
70
70
  "data-testid": "ai-preview-ago",
71
- children: [i !== "idle" && a ? /* @__PURE__ */ r("span", {
72
- className: i === "running" ? `${f} bg-[var(--color-status-success-bgSubtle)] text-status-success-text` : `${f} bg-[var(--color-status-error-bgSubtle)] text-status-error-text`,
73
- "data-testid": i === "running" ? "ai-preview-live" : "ai-preview-stopped",
74
- children: [i === "running" ? /* @__PURE__ */ r("span", {
71
+ children: [t !== "idle" && a ? /* @__PURE__ */ i("span", {
72
+ className: t === "running" ? `${f} bg-[var(--color-status-success-bgSubtle)] text-status-success-text` : `${f} bg-[var(--color-status-error-bgSubtle)] text-status-error-text`,
73
+ "data-testid": t === "running" ? "ai-preview-live" : "ai-preview-stopped",
74
+ children: [t === "running" ? /* @__PURE__ */ i("span", {
75
75
  className: "relative flex size-2",
76
- children: [/* @__PURE__ */ n("span", { className: "absolute inline-flex size-full rounded-full bg-status-success-text opacity-75 motion-safe:animate-ping" }), /* @__PURE__ */ n("span", { className: "relative inline-flex size-2 rounded-full bg-status-success-text" })]
77
- }) : /* @__PURE__ */ n("span", { className: "relative inline-flex size-2 rounded-full bg-status-error-text" }), a]
78
- }) : null, /* @__PURE__ */ r("span", { children: [
76
+ children: [/* @__PURE__ */ r("span", { className: "absolute inline-flex size-full rounded-full bg-status-success-text opacity-75 motion-safe:animate-ping" }), /* @__PURE__ */ r("span", { className: "relative inline-flex size-2 rounded-full bg-status-success-text" })]
77
+ }) : /* @__PURE__ */ r("span", { className: "relative inline-flex size-2 rounded-full bg-status-error-text" }), a]
78
+ }) : null, /* @__PURE__ */ i("span", { children: [
79
79
  o,
80
80
  " ",
81
81
  c(d)
@@ -83,6 +83,6 @@ function c({ state: i, stateLabel: a, updatedLabel: o, updatedAt: s, ago: c }) {
83
83
  });
84
84
  }
85
85
  //#endregion
86
- export { c as PreviewMeta, o as STEP_LABEL, i as formatAgo, s as previewLabels, a as useAssistantSidebarWidth };
86
+ export { l as PreviewMeta, s as STEP_LABEL, a as formatAgo, c as previewLabels, o as useAssistantSidebarWidth };
87
87
 
88
88
  //# sourceMappingURL=previewShared.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"previewShared.js","names":[],"sources":["../../../../src/bigconsole/components/preview/previewShared.tsx"],"sourcesContent":["/**\n * What is still BigConsole's about the AI preview surfaces.\n *\n * ★★★ THE SHELL, DIVIDERS AND STEP RAIL HAVE MOVED TO fe-libs\n * (`AssistantEntityPreview` / `AssistantStepRail`). They existed here so the\n * full panel and the mini panel could not drift apart; the shared component now\n * guarantees that for both, and for every other product that adopts it.\n *\n * What remains is genuinely local: BigConsole's relationship to the assistant\n * sidebar, and how it words a relative timestamp.\n *\n * Nothing here touches Apollo, React Query, or BigConsole context — it is pure\n * DOM + formatting, which is why the mini panel can live in the app shell\n * without dragging the data layer along.\n */\nimport { useEffect, useState } from 'react';\n\nimport type { AssistantEntityPreviewProps } from '@burdenoff/fe-libs/shared/assistant';\n\nimport type { PreviewStepKey } from '../../assistant/assistantRunStore';\n\n/** The `t` both panels already hold — accepted rather than imported, so this\n * file keeps no provider requirement of its own. */\ntype Translate = (key: string, fallback: string, params?: Record<string, string | number>) => string;\n\n/**\n * \"just now\" / \"40s ago\" / \"12m ago\" / \"3h ago\".\n *\n * ★★ TRANSLATED, and it now has an hour bucket. It used to return English in\n * all three locales (en, hi, ta), and a panel left open past an hour read \"240m ago\" rather\n * than \"4h ago\" — both of which were only visible on the surface that outlives\n * a build, which is exactly the one people leave sitting there.\n */\nexport function formatAgo(seconds: number, t: Translate): string {\n if (seconds < 5) return t('bigconsole.widget.aiPreview.agoJustNow', 'just now');\n if (seconds < 60) {\n return t('bigconsole.widget.aiPreview.agoSeconds', '{{n}}s ago', { n: seconds });\n }\n if (seconds < 3600) {\n return t('bigconsole.widget.aiPreview.agoMinutes', '{{n}}m ago', { n: Math.floor(seconds / 60) });\n }\n // ★ `{{n}}`, not `{n}` — fe-libs' single-brace interpolation was broken until\n // 2026.910.7 and shipped raw braces to users across the fleet. Double braces\n // are what this repo already uses (see `…aiPreviewMini.linkReady`).\n return t('bigconsole.widget.aiPreview.agoHours', '{{n}}h ago', { n: Math.floor(seconds / 3600) });\n}\n\n/**\n * Width of the assistant sidebar, or 0 when it is closed.\n *\n * Polled rather than subscribed: the widget lives in fe-libs, is mounted by the\n * app shell, and emits nothing when it opens or closes. Reading the DOM is the\n * only honest signal available, and it is cheap.\n *\n * ★★★ `enabled` IS NOT AN OPTIMISATION, IT IS THE FIX. The mini panel is\n * mounted by the app shell on every page, and a hook cannot be called below an\n * early return — so this 500ms poll ran for the lifetime of the tab on every\n * route, for every user, whether or not the assistant had ever been opened.\n * Moving the call site was impossible; making the hook do nothing was not.\n */\nexport function useAssistantSidebarWidth(enabled: boolean): number {\n const [width, setWidth] = useState(0);\n\n useEffect(() => {\n if (!enabled) {\n setWidth(0);\n return;\n }\n const measure = () => {\n const el = document.querySelector('[data-testid=\"assistant-widget-window\"][data-layout=\"sidebar\"]');\n const rect = el?.getBoundingClientRect();\n // Below `sm` the sidebar is full-width; reserving that would leave no room\n // for the preview at all, so on small screens let it stack underneath.\n const next = rect && rect.width < window.innerWidth * 0.75 ? Math.round(rect.width) : 0;\n setWidth((current) => (current === next ? current : next));\n };\n measure();\n const intervalId = window.setInterval(measure, 500);\n window.addEventListener('resize', measure);\n return () => {\n window.clearInterval(intervalId);\n window.removeEventListener('resize', measure);\n };\n }, [enabled]);\n\n return width;\n}\n\n/**\n * Step labels, reusing the TAB keys.\n *\n * ★★ They used to be English constants in the store (`PREVIEW_STEP_LABEL`), so\n * the rail rendered \"Data Sink / Dashboard / Parser / Widget\" in every locale —\n * directly beside the SAME four names rendered translated as tab labels. The\n * keys already exist and are already seeded; nothing new was needed to fix it.\n *\n * ★ Lives here because BOTH panels render the rail. It was defined twice, which\n * is the exact duplication this migration exists to remove.\n */\nexport const STEP_LABEL: Record<PreviewStepKey, { key: string; fallback: string }> = {\n datasink: { key: 'bigconsole.widget.aiPreview.tab.dataSink', fallback: 'Data Sink' },\n dashboard: { key: 'bigconsole.widget.aiPreview.tab.dashboard', fallback: 'Dashboard' },\n parser: { key: 'bigconsole.widget.aiPreview.tab.parser', fallback: 'Parser' },\n widget: { key: 'bigconsole.widget.aiPreview.tab.widget', fallback: 'Widget' },\n};\n\n/**\n * The shared surface's chrome strings, already translated.\n *\n * ★★ ONE copy, deliberately. BOTH defects this migration produced were the same\n * bug written twice — the failure caption and the reopen clock each had to be\n * fixed in the full panel AND the mini panel — so anything the two pass\n * identically belongs here rather than inlined in each. That is the same reason\n * the shell lived in this file before it moved to fe-libs.\n *\n * ★ Both surfaces use the `aiPreview` namespace, not `aiPreviewMini`: the rail\n * says the same thing wherever it is rendered, and splitting the keys would mean\n * translating \"running\" and \"failed\" twice per locale for no difference.\n *\n * `AssistantEntityPreviewProps['labels']` rather than a hand-written shape, so a\n * new label added upstream is a type error here instead of a silently missing\n * string.\n */\nexport function previewLabels(t: Translate): AssistantEntityPreviewProps['labels'] {\n const buildProgress = t('bigconsole.widget.aiPreview.buildProgress', 'Build progress');\n const skipped = t('bigconsole.widget.aiPreview.stepSkipped', 'skipped');\n return {\n // ★ main named the failure \"Build stopped\" in a hardcoded English <h3>. The\n // shared surface cannot know that word — it takes it as a label — so this\n // both restores the name AND makes it translatable for the first time.\n errorHeading: t('bigconsole.widget.aiPreview.errorHeading', 'Build stopped'),\n steps: buildProgress,\n stepsHeading: buildProgress,\n skipped,\n stepStatus: {\n pending: t('bigconsole.widget.aiPreview.stepPending', 'not started'),\n running: t('bigconsole.widget.aiPreview.stepRunning', 'running'),\n done: t('bigconsole.widget.aiPreview.stepDone', 'completed'),\n failed: t('bigconsole.widget.aiPreview.stepFailed', 'failed'),\n skipped,\n },\n };\n}\n\n/**\n * The status strip both panels hand to the shared surface as `meta`.\n *\n * ★★★ ONE copy, and this one is not a tidiness argument — the SAME DEFECT was\n * written into both panels twice over. The migration changed this chip from\n * `bg-status-success-bg` to `bg-status-success-bgSubtle` in both files, and that\n * utility DOES NOT EXIST: the token is `--color-status-success-bgSubtle` but the\n * Tailwind preset exposes it as `status-success-bg-subtle`. The app shell emits\n * `.bg-status-success-bg-subtle` and never `.bg-status-success-bgSubtle`, so the\n * \"Live\" pill lost its background entirely and became transparent text.\n * Nothing failed: an unknown utility is simply absent from the stylesheet.\n *\n * ★ Fixed with the ARBITRARY-VALUE form, `bg-[var(--color-status-…-bgSubtle)]`,\n * which is what the other ~30 sites in this repo use. It names the token\n * directly, so it cannot be broken by a preset key being spelled differently\n * from the variable — which is the entire mechanism of the bug above.\n *\n * ★★ It also carries the FAILED state, which the caption cannot. The shared\n * surface blanks `caption` whenever `error` is set — deliberately, so a rotating\n * \"Creating…\" cannot sit under a dead run — so a product that wants the failure\n * NAMED (as this one did on main, with \"Stopped\") has to say it somewhere the\n * error does not suppress. `meta` is that place: `PreviewHeader` renders it\n * without consulting `error`.\n *\n * Labels are passed in already translated, so the `t('literal.key', …)` calls\n * stay greppable at each call site and each panel keeps its own namespace.\n */\nexport function PreviewMeta({\n state,\n stateLabel,\n updatedLabel,\n updatedAt,\n ago,\n}: {\n state: 'running' | 'stopped' | 'idle';\n stateLabel: string | null;\n updatedLabel: string;\n /** When the run last changed, or null when there is nothing to age. */\n updatedAt: number | null;\n /** Renders the elapsed seconds — `formatAgo` bound to the caller's `t`. */\n ago: (seconds: number) => string;\n}) {\n /**\n * ★★★ THE CLOCK LIVES HERE, in the one element that displays it.\n *\n * It used to live in each panel, and that made a 1 Hz `setState` on the PANEL\n * — which re-rendered everything below it. `AssistantEntityPreview` calls\n * `activeTab.render()` on every render with no memo, so the Widgets tab's live\n * dashboard and every Recharts widget inside it re-rendered once a second, for\n * as long as the preview stayed open. main did not: its ticker was gated on\n * `isRunning`, so it stopped when the build did. Ungating it to fix the frozen\n * timestamp is right, but it has to cost one <span>, not the whole subtree.\n *\n * ★★ Mounting is also the gate now. The mini panel is mounted on EVERY route\n * and returns null when the full panel is up — but a hook cannot sit below an\n * early return, so its interval ran on every page regardless of whether\n * anything was shown. Owning the timer here means \"not rendered\" is \"not\n * ticking\", by construction rather than by remembering to pass a flag.\n */\n const [now, setNow] = useState(() => Date.now());\n useEffect(() => {\n if (updatedAt === null) return;\n // ★ Re-read on mount so a reopened panel cannot show the previous open's\n // reading for up to a second. See the note on lint in the git history:\n // reading the clock in render is an ESLint error (Date.now is impure).\n setNow(Date.now());\n const id = window.setInterval(() => setNow(Date.now()), 1000);\n return () => window.clearInterval(id);\n }, [updatedAt]);\n\n const agoSeconds = updatedAt === null ? 0 : Math.max(0, Math.floor((now - updatedAt) / 1000));\n\n const chip =\n 'inline-flex items-center gap-1.5 rounded-full px-2 py-0.5 text-[11px] font-semibold uppercase tracking-wide';\n return (\n <span className=\"inline-flex items-center gap-2\" data-testid=\"ai-preview-ago\">\n {state !== 'idle' && stateLabel ? (\n <span\n className={\n state === 'running'\n ? `${chip} bg-[var(--color-status-success-bgSubtle)] text-status-success-text`\n : `${chip} bg-[var(--color-status-error-bgSubtle)] text-status-error-text`\n }\n data-testid={state === 'running' ? 'ai-preview-live' : 'ai-preview-stopped'}\n >\n {state === 'running' ? (\n <span className=\"relative flex size-2\">\n <span className=\"absolute inline-flex size-full rounded-full bg-status-success-text opacity-75 motion-safe:animate-ping\" />\n <span className=\"relative inline-flex size-2 rounded-full bg-status-success-text\" />\n </span>\n ) : (\n /* ★ Still, not pulsing: the ping says \"this is happening now\", which\n is the opposite of what a stopped run means. */\n <span className=\"relative inline-flex size-2 rounded-full bg-status-error-text\" />\n )}\n {stateLabel}\n </span>\n ) : null}\n <span>\n {updatedLabel} {ago(agoSeconds)}\n </span>\n </span>\n );\n}\n"],"mappings":";;;AAiCA,SAAgB,EAAU,GAAiB,GAAsB;AAW/D,QAVI,IAAU,IAAU,EAAE,0CAA0C,WAAW,GAC3E,IAAU,KACL,EAAE,0CAA0C,cAAc,EAAE,GAAG,GAAS,CAAC,GAE9E,IAAU,OACL,EAAE,0CAA0C,cAAc,EAAE,GAAG,KAAK,MAAM,IAAU,GAAG,EAAE,CAAC,GAK5F,EAAE,wCAAwC,cAAc,EAAE,GAAG,KAAK,MAAM,IAAU,KAAK,EAAE,CAAC;;AAgBnG,SAAgB,EAAyB,GAA0B;CACjE,IAAM,CAAC,GAAO,KAAY,EAAS,EAAE;AAwBrC,QAtBA,QAAgB;AACd,MAAI,CAAC,GAAS;AACZ,KAAS,EAAE;AACX;;EAEF,IAAM,UAAgB;GAEpB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Ac,OAAO,IAAI,KAAK,IAAI,GAAG,KAAK,OAAO,IAAM,KAAa,IAAK,CAAC,EAEvF,IACJ;AACF,QACE,kBAAC,QAAD;EAAM,WAAU;EAAiC,eAAY;YAA7D,CACG,MAAU,UAAU,IACnB,kBAAC,QAAD;GACE,WACE,MAAU,YACN,GAAG,EAAK,uEACR,GAAG,EAAK;GAEd,eAAa,MAAU,YAAY,oBAAoB;aANzD,CAQG,MAAU,YACT,kBAAC,QAAD;IAAM,WAAU;cAAhB,CACE,kBAAC,QAAD,EAAM,WAAU,0GAA2G,CAAA,EAC3H,kBAAC,QAAD,EAAM,WAAU,mEAAoE,CAAA,CAC/E;QAIP,kBAAC,QAAD,EAAM,WAAU,iEAAkE,CAAA,EAEnF,EACI;OACL,MACJ,kBAAC,QAAD,EAAA,UAAA;GACG;GAAa;GAAE,EAAI,EAAW;GAC1B,EAAA,CAAA,CACF"}
1
+ {"version":3,"file":"previewShared.js","names":[],"sources":["../../../../src/bigconsole/components/preview/previewShared.tsx"],"sourcesContent":["/**\n * What is still BigConsole's about the AI preview surfaces.\n *\n * ★★★ THE SHELL, DIVIDERS AND STEP RAIL HAVE MOVED TO fe-libs\n * (`AssistantEntityPreview` / `AssistantStepRail`). They existed here so the\n * full panel and the mini panel could not drift apart; the shared component now\n * guarantees that for both, and for every other product that adopts it.\n *\n * What remains is genuinely local: BigConsole's relationship to the assistant\n * sidebar, and how it words a relative timestamp.\n *\n * Nothing here touches Apollo, React Query, or BigConsole context — it is pure\n * DOM + formatting, which is why the mini panel can live in the app shell\n * without dragging the data layer along.\n */\nimport { useEffect, useLayoutEffect, useState } from 'react';\n\nimport type { AssistantEntityPreviewProps } from '@burdenoff/fe-libs/shared/assistant';\n\nimport type { PreviewStepKey } from '../../assistant/assistantRunStore';\n\n/** The `t` both panels already hold — accepted rather than imported, so this\n * file keeps no provider requirement of its own. */\ntype Translate = (key: string, fallback: string, params?: Record<string, string | number>) => string;\n\n/**\n * \"just now\" / \"40s ago\" / \"12m ago\" / \"3h ago\".\n *\n * ★★ TRANSLATED, and it now has an hour bucket. It used to return English in\n * all three locales (en, hi, ta), and a panel left open past an hour read \"240m ago\" rather\n * than \"4h ago\" — both of which were only visible on the surface that outlives\n * a build, which is exactly the one people leave sitting there.\n */\nexport function formatAgo(seconds: number, t: Translate): string {\n if (seconds < 5) return t('bigconsole.widget.aiPreview.agoJustNow', 'just now');\n if (seconds < 60) {\n return t('bigconsole.widget.aiPreview.agoSeconds', '{{n}}s ago', { n: seconds });\n }\n if (seconds < 3600) {\n return t('bigconsole.widget.aiPreview.agoMinutes', '{{n}}m ago', { n: Math.floor(seconds / 60) });\n }\n // ★ `{{n}}`, not `{n}` — fe-libs' single-brace interpolation was broken until\n // 2026.910.7 and shipped raw braces to users across the fleet. Double braces\n // are what this repo already uses (see `…aiPreviewMini.linkReady`).\n return t('bigconsole.widget.aiPreview.agoHours', '{{n}}h ago', { n: Math.floor(seconds / 3600) });\n}\n\n/**\n * Width of the assistant sidebar, or 0 when it is closed.\n *\n * Polled rather than subscribed: the widget lives in fe-libs, is mounted by the\n * app shell, and emits nothing when it opens or closes. Reading the DOM is the\n * only honest signal available, and it is cheap.\n *\n * ★★★ `enabled` IS NOT AN OPTIMISATION, IT IS THE FIX. The mini panel is\n * mounted by the app shell on every page, and a hook cannot be called below an\n * early return — so this 500ms poll ran for the lifetime of the tab on every\n * route, for every user, whether or not the assistant had ever been opened.\n * Moving the call site was impossible; making the hook do nothing was not.\n */\nexport function useAssistantSidebarWidth(enabled: boolean): number {\n const [width, setWidth] = useState(0);\n\n /**\n * ★★★ `useLayoutEffect`, NOT `useEffect` — it has to measure BEFORE the paint\n * that reveals the panel.\n *\n * Gating the poll on `enabled` (so it stops running on every route) quietly\n * introduced a layout jump. `startRun` sets `hasRun` and `previewOpen` in the\n * SAME store update, so the render that first shows the panel is also the\n * render on which this hook is first enabled — and a passive effect has not\n * run yet, so `width` is still 0 and the panel paints one frame at full width,\n * underneath the fixed 480/560px assistant sidebar it was just launched from,\n * before snapping ~576px narrower.\n *\n * ★ The pre-gate version had no such frame, for a reason that is easy to miss:\n * the hook was UNGATED and called above the `!hasRun` early return, so the\n * poll had been running since the page mounted and `width` was already 560 long\n * before any prompt. The bug is not what the effect does — it always measured\n * synchronously — it is WHEN the effect first runs.\n *\n * A layout effect commits before the browser paints, so the first frame the\n * user sees already carries the margin. The read is one querySelector plus one\n * getBoundingClientRect; this app has no SSR, so there is no hydration warning\n * to trade against.\n */\n useLayoutEffect(() => {\n if (!enabled) {\n setWidth(0);\n return;\n }\n const measure = () => {\n const el = document.querySelector('[data-testid=\"assistant-widget-window\"][data-layout=\"sidebar\"]');\n const rect = el?.getBoundingClientRect();\n // Below `sm` the sidebar is full-width; reserving that would leave no room\n // for the preview at all, so on small screens let it stack underneath.\n const next = rect && rect.width < window.innerWidth * 0.75 ? Math.round(rect.width) : 0;\n setWidth((current) => (current === next ? current : next));\n };\n measure();\n const intervalId = window.setInterval(measure, 500);\n window.addEventListener('resize', measure);\n return () => {\n window.clearInterval(intervalId);\n window.removeEventListener('resize', measure);\n };\n }, [enabled]);\n\n return width;\n}\n\n/**\n * Step labels, reusing the TAB keys.\n *\n * ★★ They used to be English constants in the store (`PREVIEW_STEP_LABEL`), so\n * the rail rendered \"Data Sink / Dashboard / Parser / Widget\" in every locale —\n * directly beside the SAME four names rendered translated as tab labels. The\n * keys already exist and are already seeded; nothing new was needed to fix it.\n *\n * ★ Lives here because BOTH panels render the rail. It was defined twice, which\n * is the exact duplication this migration exists to remove.\n */\nexport const STEP_LABEL: Record<PreviewStepKey, { key: string; fallback: string }> = {\n datasink: { key: 'bigconsole.widget.aiPreview.tab.dataSink', fallback: 'Data Sink' },\n dashboard: { key: 'bigconsole.widget.aiPreview.tab.dashboard', fallback: 'Dashboard' },\n parser: { key: 'bigconsole.widget.aiPreview.tab.parser', fallback: 'Parser' },\n widget: { key: 'bigconsole.widget.aiPreview.tab.widget', fallback: 'Widget' },\n};\n\n/**\n * The shared surface's chrome strings, already translated.\n *\n * ★★ ONE copy, deliberately. BOTH defects this migration produced were the same\n * bug written twice — the failure caption and the reopen clock each had to be\n * fixed in the full panel AND the mini panel — so anything the two pass\n * identically belongs here rather than inlined in each. That is the same reason\n * the shell lived in this file before it moved to fe-libs.\n *\n * ★ Both surfaces use the `aiPreview` namespace, not `aiPreviewMini`: the rail\n * says the same thing wherever it is rendered, and splitting the keys would mean\n * translating \"running\" and \"failed\" twice per locale for no difference.\n *\n * `AssistantEntityPreviewProps['labels']` rather than a hand-written shape, so a\n * new label added upstream is a type error here instead of a silently missing\n * string.\n */\nexport function previewLabels(t: Translate): AssistantEntityPreviewProps['labels'] {\n const buildProgress = t('bigconsole.widget.aiPreview.buildProgress', 'Build progress');\n const skipped = t('bigconsole.widget.aiPreview.stepSkipped', 'skipped');\n return {\n // ★ main named the failure \"Build stopped\" in a hardcoded English <h3>. The\n // shared surface cannot know that word — it takes it as a label — so this\n // both restores the name AND makes it translatable for the first time.\n errorHeading: t('bigconsole.widget.aiPreview.errorHeading', 'Build stopped'),\n steps: buildProgress,\n stepsHeading: buildProgress,\n skipped,\n stepStatus: {\n pending: t('bigconsole.widget.aiPreview.stepPending', 'not started'),\n running: t('bigconsole.widget.aiPreview.stepRunning', 'running'),\n done: t('bigconsole.widget.aiPreview.stepDone', 'completed'),\n failed: t('bigconsole.widget.aiPreview.stepFailed', 'failed'),\n skipped,\n },\n };\n}\n\n/**\n * The status strip both panels hand to the shared surface as `meta`.\n *\n * ★★★ ONE copy, and this one is not a tidiness argument — the SAME DEFECT was\n * written into both panels twice over. The migration changed this chip from\n * `bg-status-success-bg` to `bg-status-success-bgSubtle` in both files, and that\n * utility DOES NOT EXIST: the token is `--color-status-success-bgSubtle` but the\n * Tailwind preset exposes it as `status-success-bg-subtle`. The app shell emits\n * `.bg-status-success-bg-subtle` and never `.bg-status-success-bgSubtle`, so the\n * \"Live\" pill lost its background entirely and became transparent text.\n * Nothing failed: an unknown utility is simply absent from the stylesheet.\n *\n * ★ Fixed with the ARBITRARY-VALUE form, `bg-[var(--color-status-…-bgSubtle)]`,\n * which is what the other ~30 sites in this repo use. It names the token\n * directly, so it cannot be broken by a preset key being spelled differently\n * from the variable — which is the entire mechanism of the bug above.\n *\n * ★★ It also carries the FAILED state, which the caption cannot. The shared\n * surface blanks `caption` whenever `error` is set — deliberately, so a rotating\n * \"Creating…\" cannot sit under a dead run — so a product that wants the failure\n * NAMED (as this one did on main, with \"Stopped\") has to say it somewhere the\n * error does not suppress. `meta` is that place: `PreviewHeader` renders it\n * without consulting `error`.\n *\n * Labels are passed in already translated, so the `t('literal.key', …)` calls\n * stay greppable at each call site and each panel keeps its own namespace.\n */\nexport function PreviewMeta({\n state,\n stateLabel,\n updatedLabel,\n updatedAt,\n ago,\n}: {\n state: 'running' | 'stopped' | 'idle';\n stateLabel: string | null;\n updatedLabel: string;\n /** When the run last changed, or null when there is nothing to age. */\n updatedAt: number | null;\n /** Renders the elapsed seconds — `formatAgo` bound to the caller's `t`. */\n ago: (seconds: number) => string;\n}) {\n /**\n * ★★★ THE CLOCK LIVES HERE, in the one element that displays it.\n *\n * It used to live in each panel, and that made a 1 Hz `setState` on the PANEL\n * — which re-rendered everything below it. `AssistantEntityPreview` calls\n * `activeTab.render()` on every render with no memo, so the Widgets tab's live\n * dashboard and every Recharts widget inside it re-rendered once a second, for\n * as long as the preview stayed open. main did not: its ticker was gated on\n * `isRunning`, so it stopped when the build did. Ungating it to fix the frozen\n * timestamp is right, but it has to cost one <span>, not the whole subtree.\n *\n * ★★ Mounting is also the gate now. The mini panel is mounted on EVERY route\n * and returns null when the full panel is up — but a hook cannot sit below an\n * early return, so its interval ran on every page regardless of whether\n * anything was shown. Owning the timer here means \"not rendered\" is \"not\n * ticking\", by construction rather than by remembering to pass a flag.\n */\n const [now, setNow] = useState(() => Date.now());\n useEffect(() => {\n if (updatedAt === null) return;\n // ★ Re-read on mount so a reopened panel cannot show the previous open's\n // reading for up to a second. See the note on lint in the git history:\n // reading the clock in render is an ESLint error (Date.now is impure).\n setNow(Date.now());\n const id = window.setInterval(() => setNow(Date.now()), 1000);\n return () => window.clearInterval(id);\n }, [updatedAt]);\n\n const agoSeconds = updatedAt === null ? 0 : Math.max(0, Math.floor((now - updatedAt) / 1000));\n\n const chip =\n 'inline-flex items-center gap-1.5 rounded-full px-2 py-0.5 text-[11px] font-semibold uppercase tracking-wide';\n return (\n <span className=\"inline-flex items-center gap-2\" data-testid=\"ai-preview-ago\">\n {state !== 'idle' && stateLabel ? (\n <span\n className={\n state === 'running'\n ? `${chip} bg-[var(--color-status-success-bgSubtle)] text-status-success-text`\n : `${chip} bg-[var(--color-status-error-bgSubtle)] text-status-error-text`\n }\n data-testid={state === 'running' ? 'ai-preview-live' : 'ai-preview-stopped'}\n >\n {state === 'running' ? (\n <span className=\"relative flex size-2\">\n <span className=\"absolute inline-flex size-full rounded-full bg-status-success-text opacity-75 motion-safe:animate-ping\" />\n <span className=\"relative inline-flex size-2 rounded-full bg-status-success-text\" />\n </span>\n ) : (\n /* ★ Still, not pulsing: the ping says \"this is happening now\", which\n is the opposite of what a stopped run means. */\n <span className=\"relative inline-flex size-2 rounded-full bg-status-error-text\" />\n )}\n {stateLabel}\n </span>\n ) : null}\n <span>\n {updatedLabel} {ago(agoSeconds)}\n </span>\n </span>\n );\n}\n"],"mappings":";;;AAiCA,SAAgB,EAAU,GAAiB,GAAsB;AAW/D,QAVI,IAAU,IAAU,EAAE,0CAA0C,WAAW,GAC3E,IAAU,KACL,EAAE,0CAA0C,cAAc,EAAE,GAAG,GAAS,CAAC,GAE9E,IAAU,OACL,EAAE,0CAA0C,cAAc,EAAE,GAAG,KAAK,MAAM,IAAU,GAAG,EAAE,CAAC,GAK5F,EAAE,wCAAwC,cAAc,EAAE,GAAG,KAAK,MAAM,IAAU,KAAK,EAAE,CAAC;;AAgBnG,SAAgB,EAAyB,GAA0B;CACjE,IAAM,CAAC,GAAO,KAAY,EAAS,EAAE;AA+CrC,QAtBA,QAAsB;AACpB,M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