@burdenoff/microfe-bigconsole 2026.912.4 → 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.
- package/dist/bigconsole/assistant/assistantApi.js +62 -55
- package/dist/bigconsole/assistant/assistantApi.js.map +1 -1
- package/dist/bigconsole/assistant/assistantRuntime.js +45 -0
- package/dist/bigconsole/assistant/assistantRuntime.js.map +1 -0
- package/dist/bigconsole/assistant/createSandboxAssistantTransport.js +197 -194
- package/dist/bigconsole/assistant/createSandboxAssistantTransport.js.map +1 -1
- package/dist/generated/wspace-operations.js +48 -37
- package/dist/generated/wspace-operations.js.map +1 -1
- package/package.json +1 -1
|
@@ -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,IAAq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OAAO,MAA0C;EAC/C,IAAM,IAAc,EAAe,EAAe;AAC7C,QAEL,MAAM,EAA4B,GAAgB,GAAa,GAAS,CAAC,EAGrE,EAAkB,YAAY,MAChC,EAAsB,KAAK,EAC3B,EAAiB,KAAK,EACtB,EAAU,UAAU;IAGxB;EAAC;EAAgB;EAAS;EAAuB;EAAiB,CACnE,EAEK,KAAgB,EACpB,OAAO,MAA+D;EACpE,IAAM,IAAc,EAAe,EAAe;AAClD,MAAI,CAAC,EAAa,QAAO,EAAE;EAC3B,IAAM,IAAO,GAAS,EAGhB,KADgB,MAAM,EAA2B,GAAa,GAAM,EAAmB,EAChE,MAAM,MAAiB,EAAa,OAAO,EAAe;AAGvF,SAFK,IAEE,EAAkB,GAAQ,GAAa,EAAK,GAF/B,EAAE;IAIxB;EAAC;EAAgB;EAAS;EAAkB,CAC7C;AAED,QAAO,SACE;EAAE;EAAY;EAAa;EAAc;EAAY;EAAe;EAAe,GAC1F;EAAC;EAAY;EAAa;EAAc;EAAY;EAAe;EAAc,CAClF"}
|
|
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,M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EAEvC,IAAgB,EACpB,OAAO,MAA0C;EAC/C,IAAM,IAAc,EAAe,EAAe;AAC7C,QAEL,MAAM,EAA4B,GAAgB,GAAa,GAAS,CAAC,EAGrE,EAAkB,YAAY,MAChC,EAAsB,KAAK,EAC3B,EAAiB,KAAK,EACtB,EAAU,UAAU;IAGxB;EAAC;EAAgB;EAAS;EAAuB;EAAiB,CACnE,EAEK,IAAgB,EACpB,OAAO,MAA+D;EACpE,IAAM,IAAc,EAAe,EAAe;AAClD,MAAI,CAAC,EAAa,QAAO,EAAE;EAC3B,IAAM,IAAO,GAAS,EAGhB,KADgB,MAAM,EAA2B,GAAa,GAAM,EAAmB,EAChE,MAAM,MAAiB,EAAa,OAAO,EAAe;AAGvF,SAFK,IAEE,EAAkB,GAAQ,GAAa,EAAK,GAF/B,EAAE;IAIxB;EAAC;EAAgB;EAAS;EAAkB,CAC7C;AAED,QAAO,SACE;EAAE;EAAY;EAAa;EAAc;EAAY;EAAe;EAAe,GAC1F;EAAC;EAAY;EAAa;EAAc;EAAY;EAAe;EAAc,CAClF"}
|
|
@@ -1853,6 +1853,17 @@ var ut = e`
|
|
|
1853
1853
|
}
|
|
1854
1854
|
}
|
|
1855
1855
|
`, mt = e`
|
|
1856
|
+
query GetReusableAssistantSandbox($id: ID!, $context: ContextInput!) {
|
|
1857
|
+
getSandbox(id: $id, context: $context) {
|
|
1858
|
+
id
|
|
1859
|
+
name
|
|
1860
|
+
status
|
|
1861
|
+
metadata
|
|
1862
|
+
template
|
|
1863
|
+
createdBy
|
|
1864
|
+
}
|
|
1865
|
+
}
|
|
1866
|
+
`, ht = e`
|
|
1856
1867
|
query GetActiveSandboxes($context: ContextInput!) {
|
|
1857
1868
|
getActiveSandboxes(context: $context) {
|
|
1858
1869
|
id
|
|
@@ -1863,7 +1874,7 @@ var ut = e`
|
|
|
1863
1874
|
createdBy
|
|
1864
1875
|
}
|
|
1865
1876
|
}
|
|
1866
|
-
`,
|
|
1877
|
+
`, gt = e`
|
|
1867
1878
|
mutation BatchUpdateWidgetPositions($updates: [WidgetPositionUpdateInput!]!) {
|
|
1868
1879
|
batchUpdateWidgetPositions(updates: $updates) {
|
|
1869
1880
|
id
|
|
@@ -1871,25 +1882,25 @@ var ut = e`
|
|
|
1871
1882
|
updatedAt
|
|
1872
1883
|
}
|
|
1873
1884
|
}
|
|
1874
|
-
`,
|
|
1885
|
+
`, _t = e`
|
|
1875
1886
|
mutation CreateEventWebhookMapping($input: CreateEventWebhookMappingInput!) {
|
|
1876
1887
|
createEventWebhookMapping(input: $input) {
|
|
1877
1888
|
...EventWebhookMappingFields
|
|
1878
1889
|
}
|
|
1879
1890
|
}
|
|
1880
|
-
${D}`,
|
|
1891
|
+
${D}`, vt = e`
|
|
1881
1892
|
mutation CreateWidget($input: BigConsoleCreateWidgetInput!) {
|
|
1882
1893
|
createBigConsoleWidget(input: $input) {
|
|
1883
1894
|
...WidgetFullFields
|
|
1884
1895
|
}
|
|
1885
1896
|
}
|
|
1886
|
-
${P}`,
|
|
1897
|
+
${P}`, yt = e`
|
|
1887
1898
|
mutation CreateWidgetAction($input: CreateWidgetActionInput!) {
|
|
1888
1899
|
createWidgetAction(input: $input) {
|
|
1889
1900
|
...WidgetActionFields
|
|
1890
1901
|
}
|
|
1891
1902
|
}
|
|
1892
|
-
${N}`,
|
|
1903
|
+
${N}`, bt = e`
|
|
1893
1904
|
mutation CreateWidgetDrilldown($sourceWidgetId: ID!, $targetDashboardId: ID!, $parameterMapping: JSON!, $navigationMode: NavigationMode = SAME_WINDOW) {
|
|
1894
1905
|
createWidgetDrilldown(
|
|
1895
1906
|
sourceWidgetId: $sourceWidgetId
|
|
@@ -1900,29 +1911,29 @@ var ut = e`
|
|
|
1900
1911
|
...WidgetDrilldownFields
|
|
1901
1912
|
}
|
|
1902
1913
|
}
|
|
1903
|
-
${A}`,
|
|
1914
|
+
${A}`, xt = e`
|
|
1904
1915
|
mutation DeleteEventWebhookMapping($id: ID!) {
|
|
1905
1916
|
deleteEventWebhookMapping(id: $id)
|
|
1906
1917
|
}
|
|
1907
|
-
`,
|
|
1918
|
+
`, St = e`
|
|
1908
1919
|
mutation DeleteWidget($id: ID!) {
|
|
1909
1920
|
deleteBigConsoleWidget(id: $id)
|
|
1910
1921
|
}
|
|
1911
|
-
`,
|
|
1922
|
+
`, Ct = e`
|
|
1912
1923
|
mutation DeleteWidgetAction($id: ID!) {
|
|
1913
1924
|
deleteWidgetAction(id: $id)
|
|
1914
1925
|
}
|
|
1915
|
-
`,
|
|
1926
|
+
`, wt = e`
|
|
1916
1927
|
mutation DeleteWidgetDrilldown($id: ID!) {
|
|
1917
1928
|
deleteWidgetDrilldown(id: $id)
|
|
1918
1929
|
}
|
|
1919
|
-
`,
|
|
1930
|
+
`, Tt = e`
|
|
1920
1931
|
mutation DuplicateWidget($id: ID!, $newPosition: WidgetPositionInput, $newTitle: String) {
|
|
1921
1932
|
duplicateWidget(id: $id, newPosition: $newPosition, newTitle: $newTitle) {
|
|
1922
1933
|
...WidgetFullFields
|
|
1923
1934
|
}
|
|
1924
1935
|
}
|
|
1925
|
-
${P}`,
|
|
1936
|
+
${P}`, Et = e`
|
|
1926
1937
|
mutation EmitWidgetEvent($input: EmitWidgetEventInput!) {
|
|
1927
1938
|
emitWidgetEvent(input: $input) {
|
|
1928
1939
|
...EventLogFields
|
|
@@ -1940,26 +1951,26 @@ e`
|
|
|
1940
1951
|
}
|
|
1941
1952
|
}
|
|
1942
1953
|
${P}`;
|
|
1943
|
-
var
|
|
1954
|
+
var Dt = e`
|
|
1944
1955
|
mutation RefreshWidgetData($widgetId: ID!) {
|
|
1945
1956
|
refreshWidgetData(widgetId: $widgetId) {
|
|
1946
1957
|
...WidgetDataFields
|
|
1947
1958
|
}
|
|
1948
1959
|
}
|
|
1949
|
-
${M}`,
|
|
1960
|
+
${M}`, Ot = e`
|
|
1950
1961
|
mutation ReorderWidgetActions($widgetId: ID!, $actionIds: [ID!]!) {
|
|
1951
1962
|
reorderWidgetActions(widgetId: $widgetId, actionIds: $actionIds) {
|
|
1952
1963
|
id
|
|
1953
1964
|
order
|
|
1954
1965
|
}
|
|
1955
1966
|
}
|
|
1956
|
-
`,
|
|
1967
|
+
`, kt = e`
|
|
1957
1968
|
mutation RetryEventDelivery($eventId: ID!) {
|
|
1958
1969
|
retryEventDelivery(eventId: $eventId) {
|
|
1959
1970
|
...EventLogFields
|
|
1960
1971
|
}
|
|
1961
1972
|
}
|
|
1962
|
-
${E}`,
|
|
1973
|
+
${E}`, At = e`
|
|
1963
1974
|
mutation TestWebhookMapping($id: ID!) {
|
|
1964
1975
|
testWebhookMapping(id: $id) {
|
|
1965
1976
|
success
|
|
@@ -1969,31 +1980,31 @@ var Et = e`
|
|
|
1969
1980
|
latencyMs
|
|
1970
1981
|
}
|
|
1971
1982
|
}
|
|
1972
|
-
`,
|
|
1983
|
+
`, jt = e`
|
|
1973
1984
|
mutation ToggleEventWebhookMapping($id: ID!, $isActive: Boolean!) {
|
|
1974
1985
|
toggleEventWebhookMapping(id: $id, isActive: $isActive) {
|
|
1975
1986
|
...EventWebhookMappingFields
|
|
1976
1987
|
}
|
|
1977
1988
|
}
|
|
1978
|
-
${D}`,
|
|
1989
|
+
${D}`, Mt = e`
|
|
1979
1990
|
mutation UpdateEventWebhookMapping($id: ID!, $input: UpdateEventWebhookMappingInput!) {
|
|
1980
1991
|
updateEventWebhookMapping(id: $id, input: $input) {
|
|
1981
1992
|
...EventWebhookMappingFields
|
|
1982
1993
|
}
|
|
1983
1994
|
}
|
|
1984
|
-
${D}`,
|
|
1995
|
+
${D}`, Nt = e`
|
|
1985
1996
|
mutation UpdateWidget($input: BigConsoleUpdateWidgetInput!) {
|
|
1986
1997
|
updateBigConsoleWidget(input: $input) {
|
|
1987
1998
|
...WidgetFullFields
|
|
1988
1999
|
}
|
|
1989
2000
|
}
|
|
1990
|
-
${P}`,
|
|
2001
|
+
${P}`, $ = e`
|
|
1991
2002
|
mutation UpdateWidgetAction($input: UpdateWidgetActionInput!) {
|
|
1992
2003
|
updateWidgetAction(input: $input) {
|
|
1993
2004
|
...WidgetActionFields
|
|
1994
2005
|
}
|
|
1995
2006
|
}
|
|
1996
|
-
${N}`,
|
|
2007
|
+
${N}`, Pt = e`
|
|
1997
2008
|
mutation UpdateWidgetDrilldown($id: ID!, $targetDashboardId: ID, $parameterMapping: JSON, $navigationMode: NavigationMode, $enabled: Boolean) {
|
|
1998
2009
|
updateWidgetDrilldown(
|
|
1999
2010
|
id: $id
|
|
@@ -2032,19 +2043,19 @@ e`
|
|
|
2032
2043
|
}
|
|
2033
2044
|
}
|
|
2034
2045
|
${D}`;
|
|
2035
|
-
var
|
|
2046
|
+
var Ft = e`
|
|
2036
2047
|
query GetWidget($id: ID!) {
|
|
2037
2048
|
getWidget(id: $id) {
|
|
2038
2049
|
...WidgetFullFields
|
|
2039
2050
|
}
|
|
2040
2051
|
}
|
|
2041
|
-
${P}`,
|
|
2052
|
+
${P}`, It = e`
|
|
2042
2053
|
query GetWidgetActions($widgetId: ID!) {
|
|
2043
2054
|
getWidgetActions(widgetId: $widgetId) {
|
|
2044
2055
|
...WidgetActionFields
|
|
2045
2056
|
}
|
|
2046
2057
|
}
|
|
2047
|
-
${N}`,
|
|
2058
|
+
${N}`, Lt = e`
|
|
2048
2059
|
query GetWidgetTypes {
|
|
2049
2060
|
getWidgetTypes {
|
|
2050
2061
|
...WidgetTypeInfoFields
|
|
@@ -2070,7 +2081,7 @@ e`
|
|
|
2070
2081
|
${A}
|
|
2071
2082
|
${j}
|
|
2072
2083
|
${M}`;
|
|
2073
|
-
var
|
|
2084
|
+
var Rt = e`
|
|
2074
2085
|
query ListEventLogs($dashboardId: ID, $widgetId: ID, $eventName: String, $status: EventStatus, $first: Int, $after: String) {
|
|
2075
2086
|
listEventLogs(
|
|
2076
2087
|
dashboardId: $dashboardId
|
|
@@ -2093,7 +2104,7 @@ var Lt = e`
|
|
|
2093
2104
|
}
|
|
2094
2105
|
}
|
|
2095
2106
|
${E}
|
|
2096
|
-
${O}`,
|
|
2107
|
+
${O}`, zt = e`
|
|
2097
2108
|
query ListEventWebhookMappings($dashboardId: ID, $widgetId: ID, $isActive: Boolean) {
|
|
2098
2109
|
listEventWebhookMappings(
|
|
2099
2110
|
dashboardId: $dashboardId
|
|
@@ -2121,13 +2132,13 @@ e`
|
|
|
2121
2132
|
}
|
|
2122
2133
|
${I}
|
|
2123
2134
|
${O}`;
|
|
2124
|
-
var
|
|
2135
|
+
var Bt = e`
|
|
2125
2136
|
query ListWidgetsByDashboard($dashboardId: ID!, $type: WidgetType) {
|
|
2126
2137
|
listWidgetsByDashboard(dashboardId: $dashboardId, type: $type) {
|
|
2127
2138
|
...WidgetListFields
|
|
2128
2139
|
}
|
|
2129
2140
|
}
|
|
2130
|
-
${F}`,
|
|
2141
|
+
${F}`, Vt = e`
|
|
2131
2142
|
query ListWidgetsForPage($pageId: ID!, $type: WidgetType) {
|
|
2132
2143
|
listWidgets(pageId: $pageId, type: $type, first: 100) {
|
|
2133
2144
|
edges {
|
|
@@ -2138,29 +2149,29 @@ var zt = e`
|
|
|
2138
2149
|
totalCount
|
|
2139
2150
|
}
|
|
2140
2151
|
}
|
|
2141
|
-
${F}`,
|
|
2152
|
+
${F}`, Ht = e`
|
|
2142
2153
|
mutation CreateWorkflow($input: CreateWorkflowInput!) {
|
|
2143
2154
|
createWorkflow(input: $input) {
|
|
2144
2155
|
...WorkflowFullFields
|
|
2145
2156
|
}
|
|
2146
2157
|
}
|
|
2147
|
-
${B}`,
|
|
2158
|
+
${B}`, Ut = e`
|
|
2148
2159
|
mutation DeleteWorkflow($id: ID!) {
|
|
2149
2160
|
deleteWorkflow(id: $id)
|
|
2150
2161
|
}
|
|
2151
|
-
`,
|
|
2162
|
+
`, Wt = e`
|
|
2152
2163
|
mutation ExecuteWorkflow($id: ID!, $triggerData: JSON) {
|
|
2153
2164
|
executeWorkflow(id: $id, triggerData: $triggerData) {
|
|
2154
2165
|
...WorkflowFullFields
|
|
2155
2166
|
}
|
|
2156
2167
|
}
|
|
2157
|
-
${B}`,
|
|
2168
|
+
${B}`, Gt = e`
|
|
2158
2169
|
mutation LinkDataSinkToWorkflow($workflowId: ID!, $input: LinkDataSinkInput!) {
|
|
2159
2170
|
linkDataSinkToWorkflow(workflowId: $workflowId, input: $input) {
|
|
2160
2171
|
...DataSinkWorkflowLinkFields
|
|
2161
2172
|
}
|
|
2162
2173
|
}
|
|
2163
|
-
${z}`,
|
|
2174
|
+
${z}`, Kt = e`
|
|
2164
2175
|
mutation UnlinkDataSinkFromWorkflow($workflowId: ID!, $dataSinkId: ID!) {
|
|
2165
2176
|
unlinkDataSinkFromWorkflow(workflowId: $workflowId, dataSinkId: $dataSinkId)
|
|
2166
2177
|
}
|
|
@@ -2172,25 +2183,25 @@ e`
|
|
|
2172
2183
|
}
|
|
2173
2184
|
}
|
|
2174
2185
|
${z}`;
|
|
2175
|
-
var
|
|
2186
|
+
var qt = e`
|
|
2176
2187
|
mutation UpdateWorkflow($id: ID!, $input: UpdateWorkflowInput!, $version: Int!) {
|
|
2177
2188
|
updateWorkflow(id: $id, input: $input, version: $version) {
|
|
2178
2189
|
...WorkflowFullFields
|
|
2179
2190
|
}
|
|
2180
2191
|
}
|
|
2181
|
-
${B}`,
|
|
2192
|
+
${B}`, Jt = e`
|
|
2182
2193
|
query GetWorkflow($id: ID!) {
|
|
2183
2194
|
workflow(id: $id) {
|
|
2184
2195
|
...WorkflowFullFields
|
|
2185
2196
|
}
|
|
2186
2197
|
}
|
|
2187
|
-
${B}`,
|
|
2198
|
+
${B}`, Yt = e`
|
|
2188
2199
|
query GetWorkflowByKey($key: String!) {
|
|
2189
2200
|
workflowByKey(key: $key) {
|
|
2190
2201
|
...WorkflowFullFields
|
|
2191
2202
|
}
|
|
2192
2203
|
}
|
|
2193
|
-
${B}`,
|
|
2204
|
+
${B}`, Xt = e`
|
|
2194
2205
|
query ListWorkflows($filter: FluidGridsWorkflowFilterInput) {
|
|
2195
2206
|
workflows(filter: $filter) {
|
|
2196
2207
|
...WorkflowListItem
|
|
@@ -2198,6 +2209,6 @@ var Kt = e`
|
|
|
2198
2209
|
}
|
|
2199
2210
|
${V}`;
|
|
2200
2211
|
//#endregion
|
|
2201
|
-
export { Ie as BatchCreateDataSinksDocument, Le as BatchDeleteDataSinksDocument,
|
|
2212
|
+
export { Ie as BatchCreateDataSinksDocument, Le as BatchDeleteDataSinksDocument, gt as BatchUpdateWidgetPositionsDocument, Z as CloneDashboardDocument, Q as CreateDashboardDocument, ne as CreateDashboardEmbedPolicyDocument, re as CreateDashboardPageDocument, ie as CreateDashboardViewDocument, Re as CreateDataSinkDocument, _t as CreateEventWebhookMappingDocument, ae as CreateGlobalFilterDocument, Je as CreateParserDocument, tt as CreatePipelineDocument, ut as CreateSandboxDocument, yt as CreateWidgetActionDocument, vt as CreateWidgetDocument, bt as CreateWidgetDrilldownDocument, Ht as CreateWorkflowDocument, Ke as DataSinkDataUpdatedDocument, qe as DataSinkUpdatedDocument, oe as DeleteDashboardDocument, se as DeleteDashboardPageDocument, ce as DeleteDashboardViewDocument, ze as DeleteDataSinkDocument, xt as DeleteEventWebhookMappingDocument, le as DeleteGlobalFilterDocument, Ye as DeleteParserDocument, nt as DeletePipelineDocument, Ct as DeleteWidgetActionDocument, St as DeleteWidgetDocument, wt as DeleteWidgetDrilldownDocument, Ut as DeleteWorkflowDocument, Tt as DuplicateWidgetDocument, Et as EmitWidgetEventDocument, Xe as ExecuteParserDocument, rt as ExecutePipelineDocument, Wt as ExecuteWorkflowDocument, Ee as ExportDashboardDocument, ft as ExtendSandboxTtlDocument, ht as GetActiveSandboxesDocument, De as GetDashboardDocument, Oe as GetDashboardViewDocument, We as GetDataSinkDataDocument, Ue as GetDataSinkDocument, ke as GetDefaultDashboardViewDocument, Qe as GetParserDocument, ot as GetPipelineDocument, st as GetPipelineExecutionDocument, mt as GetReusableAssistantSandboxDocument, pt as GetSandboxDocument, It as GetWidgetActionsDocument, Ft as GetWidgetDocument, Lt as GetWidgetTypesDocument, Yt as GetWorkflowByKeyDocument, Jt as GetWorkflowDocument, ue as ImportDashboardDocument, Be as InvalidateDataSinkCacheDocument, Gt as LinkDataSinkToWorkflowDocument, Ae as ListDashboardEmbedPoliciesDocument, je as ListDashboardSharesDocument, Me as ListDashboardViewsDocument, Ne as ListDashboardsDocument, Ge as ListDataSinksDocument, Rt as ListEventLogsDocument, zt as ListEventWebhookMappingsDocument, $e as ListParsersDocument, ct as ListPipelineExecutionsDocument, lt as ListPipelinesDocument, Pe as ListSharedWithMeDocument, Bt as ListWidgetsByDashboardDocument, Vt as ListWidgetsForPageDocument, Xt as ListWorkflowsDocument, dt as ProxySandboxRequestDocument, de as PublishDashboardEmbedPolicyDocument, Ve as RefreshDataSinkDocument, Dt as RefreshWidgetDataDocument, fe as ReorderDashboardPagesDocument, pe as ReorderGlobalFiltersDocument, Ot as ReorderWidgetActionsDocument, kt as RetryEventDeliveryDocument, me as RevokeAllSharesDocument, he as RevokeDashboardEmbedPolicyDocument, ge as RevokeDashboardShareDocument, _e as RotateDashboardEmbedPolicyDocument, ve as SetDefaultViewDocument, ye as ShareDashboardDocument, et as TestParserExpressionDocument, it as TestPipelineDocument, At as TestWebhookMappingDocument, jt as ToggleEventWebhookMappingDocument, Kt as UnlinkDataSinkFromWorkflowDocument, be as UpdateDashboardDocument, xe as UpdateDashboardEmbedPolicyDocument, Se as UpdateDashboardPageDocument, Ce as UpdateDashboardShareDocument, we as UpdateDashboardViewDocument, He as UpdateDataSinkDocument, Mt as UpdateEventWebhookMappingDocument, Te as UpdateGlobalFilterDocument, Ze as UpdateParserDocument, at as UpdatePipelineDocument, $ as UpdateWidgetActionDocument, Nt as UpdateWidgetDocument, Pt as UpdateWidgetDrilldownDocument, qt as UpdateWorkflowDocument, Fe as ValidateDashboardImportDocument, H as WorkspaceInstalledAppsDocument, W as useCreateEntityCommentMutation, K as useDeleteEntityCommentMutation, X as useGetEntityCommentsQuery, J as useResolveEntityCommentMutation };
|
|
2202
2213
|
|
|
2203
2214
|
//# sourceMappingURL=wspace-operations.js.map
|