@adminide-stack/yantra-mobile 12.0.145 → 12.0.146

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":"keepAlive.js","sources":["../../../src/screens/WebBuilderNative/keepAlive.ts"],"sourcesContent":["/**\n * Keeps an open build's sandbox awake while the app is in front and in use; an idle\n * app lets it pause (web `sandbox/keepAlive.ts`, #438 C1 - ported as is). Pure.\n */\n\nexport const KEEPALIVE_INTERVAL_MS = 10 * 60_000;\nexport const KEEPALIVE_IDLE_MS = 15 * 60_000;\nexport const KEEPALIVE_EXTEND_MS = 1_800_000;\n/** How often the hook asks the scheduler (cheap; the scheduler decides). */\nexport const KEEPALIVE_TICK_MS = 60_000;\n/** Consecutive failures (sandbox gone, network) before pinging stops for that sandbox. */\nexport const KEEPALIVE_MAX_FAILURES = 2;\n\nexport const WEBBUILDER_EXTEND_ACTION = 'WEBBUILDER_EXTEND' as const;\n\nexport type KeepAliveDecision = 'ping' | 'wait' | 'idle';\n\nexport interface KeepAliveInput {\n visible: boolean;\n sandboxId: string;\n /** The build's preview is live (not asleep, not restoring). */\n live: boolean;\n now: number;\n lastActivityAt: number;\n /** When EXTEND last went out for this sandbox; null = never. */\n lastPingAt: number | null;\n}\n\n/** `idle`: nothing should run now (hidden, idle, no live sandbox); `wait`: not due yet. */\nexport function keepAliveDecision(i: KeepAliveInput): KeepAliveDecision {\n if (!i.visible || !i.sandboxId || !i.live) return 'idle';\n if (i.now - i.lastActivityAt > KEEPALIVE_IDLE_MS) return 'idle';\n if (i.lastPingAt !== null && i.now - i.lastPingAt < KEEPALIVE_INTERVAL_MS) return 'wait';\n return 'ping';\n}\n\n/** The connector (or the proxy) does not know the action: an older version, stop asking. */\nexport function isUnsupportedActionError(message: string | null | undefined): boolean {\n return /unknown (webbuilder |sandbox )?action|unsupported action|not (a )?(known|supported) action|no such action|not mocked|action .*not allowed|invalid action/i.test(\n String(message || ''),\n );\n}\n\nexport interface ExtendResult {\n successful: boolean;\n data?: unknown;\n error?: string;\n}\n\nexport type ExtendOutcome = 'resumed' | 'alive' | 'unsupported' | 'gone' | 'failed';\n\n/** The sandbox was reclaimed, not paused (web `SANDBOX_GONE_RE`). */\nexport const SANDBOX_GONE_RE =\n /\\bSANDBOX_GONE\\b|Sandbox Not Found|Paused sandbox .+ not found|sandbox \\S+ not found|sandbox .*wasn'?t found|not found \\(404\\)|no sandbox found|does not exist|sandbox.*expired|sandbox.*killed|probably not running anymore|not running anymore|cannot be resumed|was (?:killed|deleted|destroyed)/i;\n\ntype ConnectorAnswer = { successful?: boolean; data?: unknown; error?: string | null };\n\nconst rec = (v: unknown): Record<string, unknown> =>\n v && typeof v === 'object' && !Array.isArray(v) ? (v as Record<string, unknown>) : {};\n\n/** The connector's `data` (the proxy may wrap it once more in `data`). */\nfunction answerData(r: ConnectorAnswer): Record<string, unknown> {\n const d = rec(r.data);\n return Object.keys(rec(d.data)).length ? { ...d, ...rec(d.data) } : d;\n}\n\n/**\n * A connector answer that says the sandbox no longer exists (web `isSandboxGoneResult`):\n * `errorCode: SANDBOX_NOT_FOUND` / `SANDBOX_GONE`, `data.gone` / `sandboxState: \"gone\"`, or the\n * old wording. A private sandbox refused (FORBIDDEN) is not gone.\n */\nexport function isSandboxGoneResult(r: ConnectorAnswer): boolean {\n if (r.successful) return false;\n const d = answerData(r);\n const code = String(d.errorCode ?? d.code ?? d.error_code ?? rec(r).errorCode ?? '').toUpperCase();\n if (code === 'FORBIDDEN' || /\\bFORBIDDEN\\b|sandbox is private/i.test(r.error || '')) return false;\n return (\n code === 'SANDBOX_NOT_FOUND' ||\n code === 'SANDBOX_GONE' ||\n d.gone === true ||\n d.sandboxState === 'gone' ||\n SANDBOX_GONE_RE.test(r.error || '')\n );\n}\n\n/** Where a gone sandbox can be restored from, as the connector reports it (`data.restore`, else its error text). */\nexport interface SavedCopy {\n snapshotId?: string;\n backupRepo?: string;\n backupExists?: boolean;\n}\n\nexport function savedCopyFrom(r: ConnectorAnswer): SavedCopy | null {\n if (!isSandboxGoneResult(r)) return null;\n const restore = rec(answerData(r).restore);\n const str = (v: unknown) => (typeof v === 'string' && v.trim() ? v.trim() : undefined);\n // cdecli drops `data` on a failed direct call; its message still names the snapshot and the repo.\n const text = r.error || '';\n const snapshotId =\n str(restore.snapshotId) ?? /\\bsnapshot(?:Id)?\\b[\\s:=]+[`\"']?([A-Za-z0-9][\\w.:-]{3,199})/i.exec(text)?.[1];\n const backupRepo =\n str(restore.backupRepo) ??\n /\\b(?:backupRepo|backup repo|repo)\\b[\\s:=]+[`\"']?([\\w.-]+(?:\\/[\\w.-]+)?)/i.exec(text)?.[1];\n let backupExists: boolean | undefined = backupRepo ? undefined : false;\n if (typeof restore.backupExists === 'boolean') backupExists = restore.backupExists;\n return {\n ...(snapshotId ? { snapshotId: snapshotId.replace(/[.,;)]+$/, '') } : {}),\n ...(backupRepo ? { backupRepo: backupRepo.replace(/[.,;)]+$/, '') } : {}),\n ...(backupExists !== undefined ? { backupExists } : {}),\n };\n}\n\n/** What an EXTEND answer means (`{resumed, timeoutMs}` on success). */\nexport function extendOutcome(r: ExtendResult): ExtendOutcome {\n if (r.successful) {\n const d = r.data && typeof r.data === 'object' ? (r.data as Record<string, unknown>) : {};\n return d.resumed === true ? 'resumed' : 'alive';\n }\n if (isUnsupportedActionError(r.error)) return 'unsupported';\n if (isSandboxGoneResult({ ...r, successful: false })) return 'gone';\n return 'failed';\n}\n\nexport interface KeepAliveDeps {\n now: () => number;\n extend: (sandboxId: string) => Promise<ExtendResult>;\n /** EXTEND says the sandbox is gone: the host runs its wake flow. */\n onGone?: (sandboxId: string) => void;\n /** EXTEND woke a paused sandbox: the host reloads the preview. */\n onResumed?: (sandboxId: string) => void;\n}\n\n/** One scheduler per open build; `tick()` runs EXTEND when due, one at a time. */\nexport class KeepAliveScheduler {\n private visible = true;\n\n private sandboxId = '';\n\n private live = false;\n\n private lastActivityAt: number;\n\n private lastPingAt = new Map<string, number>();\n\n private failures = new Map<string, number>();\n\n private off = new Set<string>();\n\n private inflight = false;\n\n private deps: KeepAliveDeps;\n\n constructor(deps: KeepAliveDeps) {\n this.deps = deps;\n this.lastActivityAt = deps.now();\n }\n\n noteActivity(): void {\n this.lastActivityAt = this.deps.now();\n }\n\n setVisible(visible: boolean): void {\n this.visible = visible;\n }\n\n setTarget(sandboxId: string | null | undefined, live: boolean): void {\n this.sandboxId = String(sandboxId || '').trim();\n this.live = live;\n }\n\n /** Pinging is off for this sandbox (no EXTEND on this connector, or it kept failing). */\n isOff(sandboxId = this.sandboxId): boolean {\n return this.off.has(sandboxId);\n }\n\n decision(): KeepAliveDecision {\n if (!this.sandboxId || this.off.has(this.sandboxId) || this.inflight) return 'idle';\n return keepAliveDecision({\n visible: this.visible,\n sandboxId: this.sandboxId,\n live: this.live,\n now: this.deps.now(),\n lastActivityAt: this.lastActivityAt,\n lastPingAt: this.lastPingAt.get(this.sandboxId) ?? null,\n });\n }\n\n async tick(): Promise<KeepAliveDecision | ExtendOutcome> {\n const d = this.decision();\n if (d !== 'ping') return d;\n const id = this.sandboxId;\n this.inflight = true;\n this.lastPingAt.set(id, this.deps.now());\n let outcome: ExtendOutcome;\n try {\n outcome = extendOutcome(await this.deps.extend(id));\n } catch (e) {\n outcome = extendOutcome({ successful: false, error: e instanceof Error ? e.message : String(e) });\n } finally {\n this.inflight = false;\n }\n if (outcome === 'resumed' || outcome === 'alive') {\n this.failures.delete(id);\n if (outcome === 'resumed') this.deps.onResumed?.(id);\n return outcome;\n }\n if (outcome === 'unsupported') {\n this.off.add(id);\n return outcome;\n }\n const n = (this.failures.get(id) ?? 0) + 1;\n this.failures.set(id, n);\n if (outcome === 'gone') {\n this.off.add(id);\n this.deps.onGone?.(id);\n } else if (n >= KEEPALIVE_MAX_FAILURES) {\n this.off.add(id);\n }\n return outcome;\n }\n\n /** A new sandbox came up for this build (wake, restore): try again from scratch. */\n reset(sandboxId: string): void {\n this.off.delete(sandboxId);\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AAE,CAAA;AAAA;AAEjB,IAAO,OAAA,OAAA;AAAA;AACT;AAAA,EAGA,MAAM,SAAyB,EAAA;AAC7B,IAAK,IAAA,CAAA,GAAA,CAAI,OAAO,SAAS,CAAA;AACzB,IAAK,IAAA,CAAA,QAAA,CAAS,OAAO,SAAS,CAAA;AAC9B,IAAK,IAAA,CAAA,UAAA,CAAW,OAAO,SAAS,CAAA;AAAA;AAEpC"}
1
+ {"version":3,"file":"keepAlive.js","sources":["../../../src/screens/WebBuilderNative/keepAlive.ts"],"sourcesContent":["/**\n * Keeps an open build's sandbox awake while the app is in front and in use; an idle\n * app lets it pause (web `sandbox/keepAlive.ts`, #438 C1 - ported as is). Pure.\n */\n\nexport const KEEPALIVE_INTERVAL_MS = 10 * 60_000;\nexport const KEEPALIVE_IDLE_MS = 15 * 60_000;\nexport const KEEPALIVE_EXTEND_MS = 1_800_000;\n/** How often the hook asks the scheduler (cheap; the scheduler decides). */\nexport const KEEPALIVE_TICK_MS = 60_000;\n/** Consecutive failures (sandbox gone, network) before pinging stops for that sandbox. */\nexport const KEEPALIVE_MAX_FAILURES = 2;\n\nexport const WEBBUILDER_EXTEND_ACTION = 'WEBBUILDER_EXTEND' as const;\n\nexport type KeepAliveDecision = 'ping' | 'wait' | 'idle';\n\nexport interface KeepAliveInput {\n visible: boolean;\n sandboxId: string;\n /** The build's preview is live (not asleep, not restoring). */\n live: boolean;\n now: number;\n lastActivityAt: number;\n /** When EXTEND last went out for this sandbox; null = never. */\n lastPingAt: number | null;\n}\n\n/** `idle`: nothing should run now (hidden, idle, no live sandbox); `wait`: not due yet. */\nexport function keepAliveDecision(i: KeepAliveInput): KeepAliveDecision {\n if (!i.visible || !i.sandboxId || !i.live) return 'idle';\n if (i.now - i.lastActivityAt > KEEPALIVE_IDLE_MS) return 'idle';\n if (i.lastPingAt !== null && i.now - i.lastPingAt < KEEPALIVE_INTERVAL_MS) return 'wait';\n return 'ping';\n}\n\n/** The connector (or the proxy) does not know the action: an older version, stop asking. */\nexport function isUnsupportedActionError(message: string | null | undefined): boolean {\n return /unknown (webbuilder |sandbox )?action|unsupported action|not (a )?(known|supported) action|no such action|not mocked|action .*not allowed|invalid action/i.test(\n String(message || ''),\n );\n}\n\nexport interface ExtendResult {\n successful: boolean;\n data?: unknown;\n error?: string;\n}\n\nexport type ExtendOutcome = 'resumed' | 'alive' | 'unsupported' | 'gone' | 'failed';\n\n/** The sandbox was reclaimed, not paused (web `SANDBOX_GONE_RE`). */\nexport const SANDBOX_GONE_RE =\n /\\bSANDBOX_GONE\\b|Sandbox Not Found|Paused sandbox .+ not found|sandbox \\S+ not found|sandbox .*wasn'?t found|not found \\(404\\)|no sandbox found|does not exist|sandbox.*expired|sandbox.*killed|probably not running anymore|not running anymore|cannot be resumed|was (?:killed|deleted|destroyed)/i;\n\ntype ConnectorAnswer = { successful?: boolean; data?: unknown; error?: string | null };\n\nconst rec = (v: unknown): Record<string, unknown> =>\n v && typeof v === 'object' && !Array.isArray(v) ? (v as Record<string, unknown>) : {};\n\n/** The connector's `data` (the proxy may wrap it once more in `data`). */\nfunction answerData(r: ConnectorAnswer): Record<string, unknown> {\n const d = rec(r.data);\n return Object.keys(rec(d.data)).length ? { ...d, ...rec(d.data) } : d;\n}\n\n/**\n * A connector answer that says the sandbox no longer exists (web `isSandboxGoneResult`):\n * `errorCode: SANDBOX_NOT_FOUND` / `SANDBOX_GONE`, `data.gone` / `sandboxState: \"gone\"`, or the\n * old wording. A private sandbox refused (FORBIDDEN) is not gone.\n */\nexport function isSandboxGoneResult(r: ConnectorAnswer): boolean {\n if (r.successful) return false;\n const d = answerData(r);\n const code = String(d.errorCode ?? d.code ?? d.error_code ?? rec(r).errorCode ?? '').toUpperCase();\n if (code === 'FORBIDDEN' || /\\bFORBIDDEN\\b|sandbox is private/i.test(r.error || '')) return false;\n // The project proxy has not recorded this sandbox yet: a refusal about the project, not the sandbox.\n if (/\\b(?:not found|not recorded|unknown) (?:in|for|on) this project\\b/i.test(r.error || '')) return false;\n return (\n code === 'SANDBOX_NOT_FOUND' ||\n code === 'SANDBOX_GONE' ||\n d.gone === true ||\n d.sandboxState === 'gone' ||\n SANDBOX_GONE_RE.test(r.error || '')\n );\n}\n\n/** Where a gone sandbox can be restored from, as the connector reports it (`data.restore`, else its error text). */\nexport interface SavedCopy {\n snapshotId?: string;\n backupRepo?: string;\n backupExists?: boolean;\n}\n\nexport function savedCopyFrom(r: ConnectorAnswer): SavedCopy | null {\n if (!isSandboxGoneResult(r)) return null;\n const restore = rec(answerData(r).restore);\n const str = (v: unknown) => (typeof v === 'string' && v.trim() ? v.trim() : undefined);\n // cdecli drops `data` on a failed direct call; its message still names the snapshot and the repo.\n const text = r.error || '';\n const snapshotId =\n str(restore.snapshotId) ?? /\\bsnapshot(?:Id)?\\b[\\s:=]+[`\"']?([A-Za-z0-9][\\w.:-]{3,199})/i.exec(text)?.[1];\n const backupRepo =\n str(restore.backupRepo) ??\n /\\b(?:backupRepo|backup repo|repo)\\b[\\s:=]+[`\"']?([\\w.-]+(?:\\/[\\w.-]+)?)/i.exec(text)?.[1];\n let backupExists: boolean | undefined = backupRepo ? undefined : false;\n if (typeof restore.backupExists === 'boolean') backupExists = restore.backupExists;\n return {\n ...(snapshotId ? { snapshotId: snapshotId.replace(/[.,;)]+$/, '') } : {}),\n ...(backupRepo ? { backupRepo: backupRepo.replace(/[.,;)]+$/, '') } : {}),\n ...(backupExists !== undefined ? { backupExists } : {}),\n };\n}\n\n/** What an EXTEND answer means (`{resumed, timeoutMs}` on success). */\nexport function extendOutcome(r: ExtendResult): ExtendOutcome {\n if (r.successful) {\n const d = r.data && typeof r.data === 'object' ? (r.data as Record<string, unknown>) : {};\n return d.resumed === true ? 'resumed' : 'alive';\n }\n if (isUnsupportedActionError(r.error)) return 'unsupported';\n if (isSandboxGoneResult({ ...r, successful: false })) return 'gone';\n return 'failed';\n}\n\nexport interface KeepAliveDeps {\n now: () => number;\n extend: (sandboxId: string) => Promise<ExtendResult>;\n /** EXTEND says the sandbox is gone: the host runs its wake flow. */\n onGone?: (sandboxId: string) => void;\n /** EXTEND woke a paused sandbox: the host reloads the preview. */\n onResumed?: (sandboxId: string) => void;\n}\n\n/** One scheduler per open build; `tick()` runs EXTEND when due, one at a time. */\nexport class KeepAliveScheduler {\n private visible = true;\n\n private sandboxId = '';\n\n private live = false;\n\n private lastActivityAt: number;\n\n private lastPingAt = new Map<string, number>();\n\n private failures = new Map<string, number>();\n\n private off = new Set<string>();\n\n private inflight = false;\n\n private deps: KeepAliveDeps;\n\n constructor(deps: KeepAliveDeps) {\n this.deps = deps;\n this.lastActivityAt = deps.now();\n }\n\n noteActivity(): void {\n this.lastActivityAt = this.deps.now();\n }\n\n setVisible(visible: boolean): void {\n this.visible = visible;\n }\n\n setTarget(sandboxId: string | null | undefined, live: boolean): void {\n this.sandboxId = String(sandboxId || '').trim();\n this.live = live;\n }\n\n /** Pinging is off for this sandbox (no EXTEND on this connector, or it kept failing). */\n isOff(sandboxId = this.sandboxId): boolean {\n return this.off.has(sandboxId);\n }\n\n decision(): KeepAliveDecision {\n if (!this.sandboxId || this.off.has(this.sandboxId) || this.inflight) return 'idle';\n return keepAliveDecision({\n visible: this.visible,\n sandboxId: this.sandboxId,\n live: this.live,\n now: this.deps.now(),\n lastActivityAt: this.lastActivityAt,\n lastPingAt: this.lastPingAt.get(this.sandboxId) ?? null,\n });\n }\n\n async tick(): Promise<KeepAliveDecision | ExtendOutcome> {\n const d = this.decision();\n if (d !== 'ping') return d;\n const id = this.sandboxId;\n this.inflight = true;\n this.lastPingAt.set(id, this.deps.now());\n let outcome: ExtendOutcome;\n try {\n outcome = extendOutcome(await this.deps.extend(id));\n } catch (e) {\n outcome = extendOutcome({ successful: false, error: e instanceof Error ? e.message : String(e) });\n } finally {\n this.inflight = false;\n }\n if (outcome === 'resumed' || outcome === 'alive') {\n this.failures.delete(id);\n if (outcome === 'resumed') this.deps.onResumed?.(id);\n return outcome;\n }\n if (outcome === 'unsupported') {\n this.off.add(id);\n return outcome;\n }\n const n = (this.failures.get(id) ?? 0) + 1;\n this.failures.set(id, n);\n if (outcome === 'gone') {\n this.off.add(id);\n this.deps.onGone?.(id);\n } else if (n >= KEEPALIVE_MAX_FAILURES) {\n this.off.add(id);\n }\n return outcome;\n }\n\n /** A new sandbox came up for this build (wake, restore): try again from scratch. */\n reset(sandboxId: string): void {\n this.off.delete(sandboxId);\n this.failures.delete(sandboxId);\n this.lastPingAt.delete(sandboxId);\n }\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;AAKO,MAAM,wBAAwB,EAAK,GAAA;AACnC,MAAM,oBAAoB,EAAK,GAAA;AAC/B,MAAM,mBAAsB,GAAA;AAE5B,MAAM,iBAAoB,GAAA;AAE1B,MAAM,sBAAyB,GAAA;AAC/B,MAAM,wBAA2B,GAAA;AAcjC,SAAS,kBAAkB,CAAsC,EAAA;AACtE,EAAI,IAAA,CAAC,EAAE,OAAW,IAAA,CAAC,EAAE,SAAa,IAAA,CAAC,CAAE,CAAA,IAAA,EAAa,OAAA,MAAA;AAClD,EAAA,IAAI,CAAE,CAAA,GAAA,GAAM,CAAE,CAAA,cAAA,GAAiB,mBAA0B,OAAA,MAAA;AACzD,EAAI,IAAA,CAAA,CAAE,eAAe,IAAQ,IAAA,CAAA,CAAE,MAAM,CAAE,CAAA,UAAA,GAAa,uBAA8B,OAAA,MAAA;AAClF,EAAO,OAAA,MAAA;AACT;AAGO,SAAS,yBAAyB,OAA6C,EAAA;AACpF,EAAA,OAAO,2JAA4J,CAAA,IAAA,CAAK,MAAO,CAAA,OAAA,IAAW,EAAE,CAAC,CAAA;AAC/L;AASO,MAAM,eAAkB,GAAA;AAM/B,MAAM,GAAM,GAAA,CAAC,CAAwC,KAAA,CAAA,IAAK,OAAO,CAAA,KAAM,QAAY,IAAA,CAAC,KAAM,CAAA,OAAA,CAAQ,CAAC,CAAA,GAAI,IAA+B,EAAC;AAGvI,SAAS,WAAW,CAA6C,EAAA;AAC/D,EAAM,MAAA,CAA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,IAAA,IAAI,YAAY,MAAQ,EAAA;AACtB,MAAK,IAAA,CAAA,GAAA,CAAI,IAAI,EAAE,CAAA;AACf,MAAK,CAAA,EAAA,GAAA,CAAA,EAAA,GAAA,IAAA,CAAA,IAAA,EAAK,WAAV,IAAmB,GAAA,MAAA,GAAA,EAAA,CAAA,IAAA,CAAA,EAAA,EAAA,EAAA,CAAA;AAAA,KACrB,MAAA,IAAW,KAAK,sBAAwB,EAAA;AACtC,MAAK,IAAA,CAAA,GAAA,CAAI,IAAI,EAAE,CAAA;AAAA;AAEjB,IAAO,OAAA,OAAA;AAAA;AACT;AAAA,EAGA,MAAM,SAAyB,EAAA;AAC7B,IAAK,IAAA,CAAA,GAAA,CAAI,OAAO,SAAS,CAAA;AACzB,IAAK,IAAA,CAAA,QAAA,CAAS,OAAO,SAAS,CAAA;AAC9B,IAAK,IAAA,CAAA,UAAA,CAAW,OAAO,SAAS,CAAA;AAAA;AAEpC"}
@@ -1,4 +1,4 @@
1
- import {useRef,useState,useCallback,useMemo,useEffect,useSyncExternalStore}from'react';import {useApolloClient,gql}from'@apollo/client/index.js';import {useAiCodeDeployToCloudflareMutation}from'common/graphql';import {v4}from'uuid';import AsyncStorage from'@react-native-async-storage/async-storage';import {projectInstructionsNote,readDeleteReply,readSettingsUpdateReply,parseProjectSettings}from'../../features/webbuilder/projectTools.js';import {useCdecliConnection}from'../../contexts/CdecliConnectionContext.js';import {useChatStream}from'../../hooks/useChatStream.js';import {useHostChatChannel}from'../../hooks/useHostChatChannel.js';import {config}from'../../config/env-config.js';import {useChatMessages,subscribeRememberedHistory,historyRunningChannelIds}from'../../hooks/useChatApi.js';import {usePrerequisiteIds}from'../../hooks/usePrerequisiteIds.js';import {useCanvasSession}from'../../features/canvas/useCanvasSession.js';import {tokenClaims}from'../../features/canvas/sessionIdentity.js';import {buildsFromPosts,hasWorkflowPosts,siteNameFromRequest,titleFromPrompt,stripAgentNote,projectFromPosts,turnState,pendingWork,transcriptFromPosts,userBubbleText,displayAgentText}from'../../features/webbuilder/buildFragments.js';import {handEditsNote,savedCodeSource}from'../../features/webbuilder/codeFiles.js';import {createCodeWorkspace}from'./codeWorkspaceApi.js';import {WEBBUILDER_CHAT_SKILL,buildTriggerParams,templateRemixNote,newObjectId}from'../../features/webbuilder/workflow.js';import {useWebBuilderGallery}from'./useWebBuilderGallery.js';import {agentEditNote,agentPublishMessage}from'../../features/webbuilder/webbuilderPrompts.js';import {useCodeAssistantCatalog}from'./useCodeAssistantCatalog.js';import {useConnectorTemplates}from'./useConnectorTemplates.js';import {directChannels,uploadAttachment,triggerBuild,createSandboxRouter,directSandboxRun,wakeSandbox,restoreFromSavedCopy,OUTDATED_SERVER_RE}from'./webbuilderTransport.js';import {useSandboxProxyApi}from'./sandboxProxyApi.js';import {useSandboxKeepAlive}from'./useSandboxKeepAlive.js';import {pendingAskUser}from'../../features/chat/askUser.js';import {runningBuild,useRunningBuilds,markBuildDone}from'./runningBuilds.js';import {isAgentSite}from'./siteLane.js';import {undoLastChange,redoChange}from'./versionUndo.js';import {WEBBUILDER_EXPORT_ZIP_ACTION,exportZipParams,exportZipUrl}from'../../features/webbuilder/exportCode.js';import {useRestoredSandboxes,applyRestored}from'./useRestoredSandboxes.js';import {useWebBuilderJobs}from'./useWebBuilderJobs.js';var __defProp = Object.defineProperty;
1
+ import {useRef,useState,useCallback,useMemo,useEffect,useSyncExternalStore}from'react';import {useApolloClient,gql}from'@apollo/client/index.js';import {useAiCodeDeployToCloudflareMutation}from'common/graphql';import {v4}from'uuid';import AsyncStorage from'@react-native-async-storage/async-storage';import {projectInstructionsNote,readDeleteReply,readSettingsUpdateReply,parseProjectSettings}from'../../features/webbuilder/projectTools.js';import {useCdecliConnection}from'../../contexts/CdecliConnectionContext.js';import {useChatStream}from'../../hooks/useChatStream.js';import {useHostChatChannel}from'../../hooks/useHostChatChannel.js';import {useHostChatSteering}from'../../hooks/useHostChatSteering.js';import {config}from'../../config/env-config.js';import {useChatMessages,subscribeRememberedHistory,historyRunningChannelIds}from'../../hooks/useChatApi.js';import {usePrerequisiteIds}from'../../hooks/usePrerequisiteIds.js';import {useCanvasSession}from'../../features/canvas/useCanvasSession.js';import {tokenClaims}from'../../features/canvas/sessionIdentity.js';import {buildsFromPosts,hasWorkflowPosts,siteNameFromRequest,titleFromPrompt,stripAgentNote,projectFromPosts,turnState,pendingWork,transcriptFromPosts,userBubbleText,displayAgentText}from'../../features/webbuilder/buildFragments.js';import {handEditsNote,savedCodeSource}from'../../features/webbuilder/codeFiles.js';import {createCodeWorkspace}from'./codeWorkspaceApi.js';import {WEBBUILDER_CHAT_SKILL,buildTriggerParams,templateRemixNote,newObjectId}from'../../features/webbuilder/workflow.js';import {useWebBuilderGallery}from'./useWebBuilderGallery.js';import {agentEditNote,agentPublishMessage}from'../../features/webbuilder/webbuilderPrompts.js';import {useCodeAssistantCatalog}from'./useCodeAssistantCatalog.js';import {useConnectorTemplates}from'./useConnectorTemplates.js';import {directChannels,uploadAttachment,triggerBuild,createSandboxRouter,directSandboxRun,wakeSandbox,restoreFromSavedCopy,OUTDATED_SERVER_RE}from'./webbuilderTransport.js';import {useSandboxProxyApi}from'./sandboxProxyApi.js';import {useSandboxKeepAlive}from'./useSandboxKeepAlive.js';import {pendingAskUser}from'../../features/chat/askUser.js';import {runningBuild,useRunningBuilds,markBuildDone}from'./runningBuilds.js';import {isAgentSite}from'./siteLane.js';import {undoLastChange,redoChange}from'./versionUndo.js';import {WEBBUILDER_EXPORT_ZIP_ACTION,exportZipParams,exportZipUrl}from'../../features/webbuilder/exportCode.js';import {useRestoredSandboxes,applyRestored}from'./useRestoredSandboxes.js';import {useWebBuilderJobs}from'./useWebBuilderJobs.js';var __defProp = Object.defineProperty;
2
2
  var __defProps = Object.defineProperties;
3
3
  var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
4
4
  var __getOwnPropSymbols = Object.getOwnPropertySymbols;
@@ -90,6 +90,9 @@ const PRE_PUBLISH_REVIEW_QUERY = gql`
90
90
  function notSetUp(org) {
91
91
  return `Builds are not set up for ${org || "this workspace"} yet. Ask an admin to configure the Code Assistant templates.`;
92
92
  }
93
+ function mayHaveStarted(error) {
94
+ return /timed? ?out|timeout|deadline|network|fetch|abort|socket|ECONN|EPIPE|\b50[234]\b|gateway|unavailable/i.test(error);
95
+ }
93
96
  function failureText(error) {
94
97
  if (/\b401\b|unauthori[sz]ed/i.test(error)) return "Your sign-in was not accepted. Try again in a moment.";
95
98
  if (/network|fetch|timed out/i.test(error)) return "Couldn't reach the build service. Check your connection and try again.";
@@ -130,7 +133,8 @@ function useWebBuilderHost(routeOrg) {
130
133
  const projectIds = useRef(/* @__PURE__ */ new Map());
131
134
  const {
132
135
  posts: rawPosts,
133
- refetch
136
+ refetch,
137
+ messagesLoaded
134
138
  } = useChatMessages(activeChannelId);
135
139
  const posts = useMemo(() => activeChannelId ? rawPosts : [], [activeChannelId, rawPosts]);
136
140
  const activeProject = projects.find((p) => p.channelId === activeChannelId);
@@ -216,6 +220,7 @@ function useWebBuilderHost(routeOrg) {
216
220
  return run;
217
221
  }, [adoptAgentProject]);
218
222
  const instructionsByChannel = useRef(/* @__PURE__ */ new Map());
223
+ const importedChannels = useRef(/* @__PURE__ */ new Set());
219
224
  const jobs = useWebBuilderJobs(effectiveOrg);
220
225
  const agentJob = useRef(null);
221
226
  const sendAgentTurn = useCallback((channelId, text, files, task) => {
@@ -371,6 +376,25 @@ ${projectInstructionsNote(knowledge)}` : text;
371
376
  }, POLL_MS);
372
377
  return () => clearInterval(timer);
373
378
  }, [turn, refetch, jobs]);
379
+ const latestChat = useRef({
380
+ channelId: activeChannelId,
381
+ refetch,
382
+ postCount: posts.length
383
+ });
384
+ latestChat.current = {
385
+ channelId: activeChannelId,
386
+ refetch,
387
+ postCount: posts.length
388
+ };
389
+ const canFallBackToAgent = useCallback(async (error, channelId) => {
390
+ var _a2, _b2;
391
+ if (!error || /not set up|signing in/i.test(error) || mayHaveStarted(error)) return false;
392
+ const chatNow = latestChat.current;
393
+ if (chatNow.channelId !== channelId) return false;
394
+ const fresh = await chatNow.refetch().catch(() => null);
395
+ const rows = (_b2 = (_a2 = fresh == null ? void 0 : fresh.data) == null ? void 0 : _a2.messages) == null ? void 0 : _b2.data;
396
+ return !((rows == null ? void 0 : rows.length) || latestChat.current.postCount);
397
+ }, []);
374
398
  const runTurn = useCallback(async (opts) => {
375
399
  var _a2, _b2, _c2, _d2, _e2, _f2;
376
400
  const {
@@ -486,9 +510,27 @@ ${templateRemixNote(request.template)}` : request.text,
486
510
  if (error && /not set up|signing in/i.test(error)) {
487
511
  setActiveChannelId(null);
488
512
  setStartError(error);
513
+ return;
489
514
  }
515
+ return canFallBackToAgent(error, channelId).then((fallBack) => {
516
+ if (!fallBack) return;
517
+ const id = v4();
518
+ agentChannels.current.add(id);
519
+ unsavedAgentChannels.current.add(id);
520
+ pendingAgentTurn.current = {
521
+ channelId: id,
522
+ text: request.text,
523
+ files: request.attachments,
524
+ job: {
525
+ mode: "new"
526
+ }
527
+ };
528
+ setTurnError(null);
529
+ setActiveChannelId(id);
530
+ setAgentChannelId(id);
531
+ });
490
532
  }).catch(() => void 0);
491
- }, [runTurn, catalog.defaults]);
533
+ }, [runTurn, catalog.defaults, canFallBackToAgent]);
492
534
  const openProject = useCallback((channelId) => {
493
535
  setTurnError(null);
494
536
  setActiveChannelId(channelId);
@@ -636,15 +678,39 @@ ${agentEditNote(target)}` : ""}${editsNote}`;
636
678
  template: null,
637
679
  edit: target != null ? target : null,
638
680
  attachments
681
+ }).then(async (error) => {
682
+ if (target || builds.length || !await canFallBackToAgent(error, channelId)) return;
683
+ agentChannels.current.add(channelId);
684
+ if (!posts.length) unsavedAgentChannels.current.add(channelId);
685
+ setTurnError(null);
686
+ const job = {
687
+ mode: "new",
688
+ siteTitle: (activeProject == null ? void 0 : activeProject.title) || null
689
+ };
690
+ if (agentChannelId === channelId) {
691
+ sendAgentTurn(channelId, `${text}${editsNote}`, attachments, job);
692
+ return;
693
+ }
694
+ pendingAgentTurn.current = {
695
+ channelId,
696
+ text: `${text}${editsNote}`,
697
+ files: attachments,
698
+ job
699
+ };
700
+ setAgentChannelId(channelId);
639
701
  }).catch(() => void 0);
640
- }, [activeChannelId, agentLane, agentChannelId, catalog.defaults, builds, activeProject == null ? void 0 : activeProject.title, runTurn, sendAgentTurn, chat]);
641
- const agentMessages = useMemo(() => chat.messages.map((m, index) => ({
702
+ }, [activeChannelId, agentLane, agentChannelId, catalog.defaults, builds, activeProject == null ? void 0 : activeProject.title, runTurn, sendAgentTurn, chat, posts.length, canFallBackToAgent]);
703
+ const {
704
+ visibleMessages: steeredMessages,
705
+ steering
706
+ } = useHostChatSteering(chat, userBubbleText);
707
+ const agentMessages = useMemo(() => steeredMessages.map((m, index) => ({
642
708
  id: `${m.role}-${index}`,
643
709
  role: m.role,
644
710
  // The template note is for the agent; the person sees what they typed.
645
711
  content: m.role === "user" ? userBubbleText(m.content) : displayAgentText(m.content),
646
712
  attachments: m.attachments
647
- })).filter((m) => m.role === "user" || m.content.trim()), [chat.messages]);
713
+ })).filter((m) => m.role === "user" || m.content.trim()), [steeredMessages]);
648
714
  const withOpenRun = useCallback((rows) => {
649
715
  if (!openRunPending || !(openRun == null ? void 0 : openRun.ask)) return rows;
650
716
  const {
@@ -667,7 +733,8 @@ ${agentEditNote(target)}` : ""}${editsNote}`;
667
733
  error: chat.error,
668
734
  connected: cdecli.channelConnected,
669
735
  ask: pendingAsk,
670
- send
736
+ send,
737
+ steering
671
738
  } : {
672
739
  messages: withOpenRun(messages),
673
740
  streaming: running ? progress || (building == null ? void 0 : building.statusText) || "Working on it\u2026" : openRunStreaming,
@@ -676,7 +743,7 @@ ${agentEditNote(target)}` : ""}${editsNote}`;
676
743
  connected: Boolean(token),
677
744
  ask: pendingAsk,
678
745
  send
679
- }, [agentLane, agentMessages, pendingAsk, withOpenRun, openRunStreaming, openRunPending, chat.response, agentBusy, chat.error, cdecli.channelConnected, messages, running, progress, building == null ? void 0 : building.statusText, turnError, session.ready, session.error, token, send]);
746
+ }, [agentLane, agentMessages, steering, pendingAsk, withOpenRun, openRunStreaming, openRunPending, chat.response, agentBusy, chat.error, cdecli.channelConnected, messages, running, progress, building == null ? void 0 : building.statusText, turnError, session.ready, session.error, token, send]);
680
747
  const recordedSandboxRef = useRef(/* @__PURE__ */ new Set());
681
748
  const {
682
749
  recordAgentBuild
@@ -798,7 +865,9 @@ ${agentEditNote(target)}` : ""}${editsNote}`;
798
865
  message: "There is nothing to undo yet."
799
866
  };
800
867
  noteActivity();
801
- const outcome = await undoLastChange(sandboxCall, build.sandboxId);
868
+ const outcome = await undoLastChange(sandboxCall, build.sandboxId, {
869
+ keepEarlier: Boolean(activeChannelId && importedChannels.current.has(activeChannelId))
870
+ });
802
871
  if (outcome.redo) redoFor.current.set(build.key, outcome.redo);
803
872
  else redoFor.current.delete(build.key);
804
873
  return {
@@ -807,7 +876,7 @@ ${agentEditNote(target)}` : ""}${editsNote}`;
807
876
  canRedo: Boolean(outcome.redo),
808
877
  askAgent: Boolean(outcome.listFailed) && build.origin === "agent"
809
878
  };
810
- }, [sandboxCall, noteActivity]);
879
+ }, [sandboxCall, noteActivity, activeChannelId]);
811
880
  const redo = useCallback(async (build) => {
812
881
  const version = redoFor.current.get(build.key);
813
882
  if (!build.sandboxId || !version) return {
@@ -862,6 +931,7 @@ ${agentEditNote(target)}` : ""}${editsNote}`;
862
931
  const raw = (_b2 = (_a2 = result.data) == null ? void 0 : _a2.aiCodeProjectSettings) != null ? _b2 : null;
863
932
  const settings = parseProjectSettings(raw);
864
933
  if (settings) instructionsByChannel.current.set(channelId, settings.instructions);
934
+ if (settings == null ? void 0 : settings.imported) importedChannels.current.add(channelId);
865
935
  return raw;
866
936
  },
867
937
  updateSettings: async (channelId, patch) => {
@@ -1082,6 +1152,7 @@ ${agentEditNote(target)}` : ""}${editsNote}`;
1082
1152
  startProject,
1083
1153
  builds,
1084
1154
  buildsLoading: activeChannelId !== null && posts.length === 0 && !running,
1155
+ historyLoading: activeChannelId !== null && !messagesLoaded && !unsavedAgentChannels.current.has(activeChannelId) && !running,
1085
1156
  building,
1086
1157
  publishing: work === "publishing",
1087
1158
  hostChat,
@@ -1096,4 +1167,4 @@ ${agentEditNote(target)}` : ""}${editsNote}`;
1096
1167
  projectTools,
1097
1168
  code
1098
1169
  };
1099
- }export{useWebBuilderHost};//# sourceMappingURL=useWebBuilderHost.js.map
1170
+ }export{mayHaveStarted,useWebBuilderHost};//# sourceMappingURL=useWebBuilderHost.js.map