diff --git a/.changeset/connection-error-handling.md b/.changeset/connection-error-handling.md
new file mode 100644
index 0000000000..9ea4e94e22
--- /dev/null
+++ b/.changeset/connection-error-handling.md
@@ -0,0 +1,5 @@
+---
+'@conciv/contract': patch
+---
+
+Global engine-reachability handling: reachability seam + single rebindable rpc client factory in contract, router error boundary with /panel/latest sentinel, one standing offline notice per window context, composer send disabled while unreachable.
diff --git a/.fallowrc.json b/.fallowrc.json
index 96b1c139e5..d4382b29d2 100644
--- a/.fallowrc.json
+++ b/.fallowrc.json
@@ -7,6 +7,7 @@
"**/*.d.ts",
"**/*.generated.ts",
"packages/aidx/**",
+ "packages/contract/test/helpers/fake-native-socket.ts",
"packages/extensions/tanstack/test/fixtures/**",
"packages/oxlint-plugin/test/fixtures/**",
"packages/oxlint-plugin/fixtures/**",
diff --git a/apps/conciv/package.json b/apps/conciv/package.json
index cb38638938..178e4aeee7 100644
--- a/apps/conciv/package.json
+++ b/apps/conciv/package.json
@@ -61,6 +61,7 @@
"@orpc/server": "catalog:",
"@solidjs/testing-library": "^0.8.10",
"@tanstack/ai": "catalog:",
+ "@tanstack/query-core": "^5.80.2",
"@tanstack/router-cli": "^1.167.18",
"@tanstack/router-plugin": "^1.168.19",
"@types/node": "^26.1.0",
diff --git a/apps/conciv/src/app/context.ts b/apps/conciv/src/app/context.ts
index f9b110073a..708b836b16 100644
--- a/apps/conciv/src/app/context.ts
+++ b/apps/conciv/src/app/context.ts
@@ -27,6 +27,7 @@ export type AppContextValue = {
disconnect?: () => void
grabProvider?: GrabProvider
connectionGeneration: () => number
+ apiBase: () => string
}
export const AppContext = createContext()
@@ -96,3 +97,7 @@ export function useGrabProvider(): GrabProvider | undefined {
export function useConnectionGeneration(): () => number {
return useAppScope('useConnectionGeneration', (app) => app.connectionGeneration)
}
+
+export function useApiBase(): () => string {
+ return useAppScope('useApiBase', (app) => app.apiBase)
+}
diff --git a/apps/conciv/src/app/reachability.ts b/apps/conciv/src/app/reachability.ts
new file mode 100644
index 0000000000..ddb95fb528
--- /dev/null
+++ b/apps/conciv/src/app/reachability.ts
@@ -0,0 +1,19 @@
+import {createContext, useContext, type Accessor} from 'solid-js'
+import {engineOnline, sustainedEngineOffline} from '@conciv/client'
+
+export type EngineReachability = {
+ online: Accessor
+ sustainedOffline: Accessor
+}
+
+export const EngineReachabilityContext = createContext()
+
+export function makeEngineReachability(): EngineReachability {
+ return {online: engineOnline(), sustainedOffline: sustainedEngineOffline()}
+}
+
+export function useEngineReachability(): EngineReachability {
+ const value = useContext(EngineReachabilityContext)
+ if (!value) throw new Error('useEngineReachability called outside EngineReachabilityContext.Provider')
+ return value
+}
diff --git a/apps/conciv/src/composer/actions.tsx b/apps/conciv/src/composer/actions.tsx
index 417829593c..a7e3894a9c 100644
--- a/apps/conciv/src/composer/actions.tsx
+++ b/apps/conciv/src/composer/actions.tsx
@@ -7,7 +7,8 @@ import SquarePen from 'lucide-solid/icons/square-pen'
import {getHostApi} from '@conciv/extension'
import type {Grab} from '@conciv/grab'
import {useAppData} from '../app/context.js'
-import {notify} from '../shell/notices.js'
+import {useNotices} from '../shell/notice-context.js'
+import type {Notify} from '../shell/notices.js'
import {LaunchMenu} from './launch-menu.js'
import {terminalRpc} from './terminal-rpc.js'
@@ -26,7 +27,7 @@ function errorCode(error: unknown): string | null {
return null
}
-async function copyCommand(command: string): Promise {
+async function copyCommand(notify: Notify, command: string): Promise {
try {
await navigator.clipboard.writeText(command)
notify('Command copied. Paste it in your terminal.')
@@ -43,6 +44,7 @@ export function ComposerActions(props: {
onStageGrab: (grab: Grab) => void
}): JSX.Element {
const appData = useAppData()
+ const notices = useNotices()
const grab = getHostApi().useGrab()
const toast = getHostApi().useToast()
const meta = useQuery(() => appData.utils.meta.models.queryOptions())
@@ -78,18 +80,18 @@ export function ComposerActions(props: {
},
onSuccess: async (outcome: LaunchOutcome) => {
if (outcome.opened) {
- notify(`Opened in ${harnessName()}.`)
+ notices.notify(`Opened in ${harnessName()}.`)
return
}
- if (outcome.command) await copyCommand(outcome.command)
+ if (outcome.command) await copyCommand(notices.notify, outcome.command)
},
- onError: (error: unknown) => notify(launchFailure(error), {tone: 'warn'}),
+ onError: (error: unknown) => notices.notify(launchFailure(error), {tone: 'warn'}),
}))
const copyConnect = useMutation(() => ({
mutationFn: () => terminal.connectCommand({sessionId: props.sessionId}),
- onSuccess: (result: {command: string}) => void copyCommand(result.command),
- onError: (error: unknown) => notify(launchFailure(error), {tone: 'warn'}),
+ onSuccess: (result: {command: string}) => void copyCommand(notices.notify, result.command),
+ onError: (error: unknown) => notices.notify(launchFailure(error), {tone: 'warn'}),
}))
return (
diff --git a/apps/conciv/src/entry-standalone.tsx b/apps/conciv/src/entry-standalone.tsx
index c65d5db6cd..45984986c4 100644
--- a/apps/conciv/src/entry-standalone.tsx
+++ b/apps/conciv/src/entry-standalone.tsx
@@ -10,10 +10,11 @@ function start(): void {
const apiBase = params.get('core') ?? ''
window.__CONCIV_API_BASE__ = apiBase
const router = createConcivRouter({
- rpc: makeBrowserRpcClient(apiBase, {transport: settings.transport}),
+ rpc: makeBrowserRpcClient(apiBase, {transport: settings.transport}).rpc,
history: createBrowserHistory(),
environment: {rootNode: document, document},
settings,
+ apiBase: () => apiBase,
})
const root = document.getElementById('app')
if (root) render(() => , root)
diff --git a/apps/conciv/src/pane/chat-pane.tsx b/apps/conciv/src/pane/chat-pane.tsx
index 5230d6f036..79d6cbf0ae 100644
--- a/apps/conciv/src/pane/chat-pane.tsx
+++ b/apps/conciv/src/pane/chat-pane.tsx
@@ -11,7 +11,7 @@ import {
untrack,
type JSX,
} from 'solid-js'
-import {useMutation, useQuery} from '@tanstack/solid-query'
+import {useQuery} from '@tanstack/solid-query'
import {useChatSession} from '@conciv/client'
import {
AttachmentByMime,
@@ -30,9 +30,8 @@ import {PAGE_ACT_TOOL_NAMES, PAGE_TOOL_PREFIX} from '@conciv/extension-page/defs
import {builtinToolCards, nowTitle} from '@conciv/ui-kit-chat-tools'
import {concivToolCards} from '@conciv/tools/cards'
import {coreToolCards} from '@conciv/core/cards'
-import type {MessagePart, MultimodalContent, ToolCallPart, ToolResultPart} from '@tanstack/ai-client'
+import type {MessagePart, ToolCallPart, ToolResultPart} from '@tanstack/ai-client'
import type {ToolCardEntry, ToolCatalogView} from '@conciv/protocol/tool-view-types'
-import type {UiAnswerValue} from '@conciv/protocol/ui-types'
import type {MarkerRow} from '@conciv/contract'
import {collectToolRenderers, HostApiProvider} from '@conciv/extension'
import type {Grab} from '@conciv/grab'
@@ -52,14 +51,13 @@ import {ExtensionSurface} from '../extension/extension-slots.js'
import {makePaneGrabApi} from '../extension/pane-grab.js'
import {ComposerActions} from '../composer/actions.js'
import {SessionModelSelector} from '../composer/model-selector.js'
-import {NoticeToaster, notify} from '../shell/notices.js'
-import {EngineStaleNotice} from '../shell/engine-notice.js'
+import {useEngineNotices} from '../shell/notice-context.js'
import {makeDraftStorage} from './draft-storage.js'
import {useSessionCaptures} from './session-captures.js'
import {makeToolViewCtx} from './tool-view-ctx.js'
import type {ComposerInputHandle} from './composer-input-adapter.js'
import {PaneComposer} from './pane-composer.js'
-import {checkSend, type SendVerdict} from './send-checks.js'
+import {usePaneMessaging} from './use-pane-messaging.js'
const GRAB_PREVIEW_MAX_W = 280
@@ -73,21 +71,6 @@ const ERROR = 'flex gap-2 items-center text-pw-danger text-[0.75rem] anim-msg'
const RETRY =
'py-1.5 px-2.5 min-h-8 rounded-[0.4375rem] border border-pw-danger-line bg-transparent text-pw-danger cursor-pointer font-semibold text-[0.75rem] leading-none font-pw shrink-0 trans-bg hover:bg-pw-danger-14'
-type SendRejection = {rejected: true; message: string | null; tone: 'info' | 'warn'}
-
-function sendRejection(verdict: Extract): SendRejection {
- return {rejected: true, message: verdict.message, tone: verdict.tone}
-}
-
-function isSendRejection(failure: unknown): failure is SendRejection {
- return typeof failure === 'object' && failure !== null && 'rejected' in failure && failure.rejected === true
-}
-
-function failureMessage(failure: unknown): string {
- if (failure instanceof Error && failure.message.length > 0) return failure.message
- return 'The message could not be sent.'
-}
-
function resetSlideOnSelf(reset: () => void) {
return (event: AnimationEvent) => {
if (event.target === event.currentTarget) reset()
@@ -138,6 +121,7 @@ export function ChatPane(props: {sessionId: string}): JSX.Element {
const appData = useAppData()
const announce = useAnnounce()
const connected = useConnected()
+ const {reachability, notices} = useEngineNotices()
const instances = useInstances()
const pane = usePane()
const sessionId = untrack(() => props.sessionId)
@@ -175,18 +159,23 @@ export function ChatPane(props: {sessionId: string}): JSX.Element {
{},
)
- const uiReply = useMutation(() => ({
- mutationFn: (input: {toolCallId: string; value: UiAnswerValue}) =>
- rpc.chat.uiReply({sessionId, toolCallId: input.toolCallId, value: input.value}),
- onError: () => notify('That question is no longer waiting for an answer.'),
- }))
+ const messaging = usePaneMessaging({
+ rpc,
+ sessionId,
+ chat,
+ appData,
+ reachability,
+ notices,
+ grabStore: pane.grabStore,
+ refetchMarkers: () => markers.refetch(),
+ })
const toolCtx = makeToolViewCtx({
rpc,
harnessId: () => (meta.isPending ? '' : (meta.data?.harness.id ?? '')),
catalog,
sendMessage: (text) => void chat.sendMessage(text),
- addResult: (toolCallId, value) => uiReply.mutate({toolCallId, value}),
+ addResult: (toolCallId, value) => messaging.uiReply.mutate({toolCallId, value}),
durationFor: (toolCallId) => durations()[toolCallId],
captureFor: captures.lookup,
})
@@ -223,20 +212,7 @@ export function ChatPane(props: {sessionId: string}): JSX.Element {
return now
}, false)
- const visibleError = () => {
- const error = chat.error()
- return error && error.message !== 'stopped' ? error : undefined
- }
-
- const compact = useMutation(() => ({
- mutationFn: () => rpc.sessions.compact({sessionId}),
- onError: () => notify('Compaction failed. The session may be busy. Try again in a moment.'),
- onSettled: () => {
- appData.invalidateSessions()
- void markers.refetch()
- },
- }))
- const compacting = () => compact.isPending
+ const compacting = messaging.compacting
const triggerSources = useComposerTriggerSources(sessionId)
const focusInput = () => requestAnimationFrame(() => inputHandle()?.focus())
@@ -279,23 +255,6 @@ export function ChatPane(props: {sessionId: string}): JSX.Element {
const dividersInRange = (start: number, end: number): MarkerRow[] =>
(markers.data ?? []).filter((row) => row.afterTurn >= start && row.afterTurn <= end)
- const onSend = async (content: string | MultimodalContent) => {
- const verdict = checkSend(content, {
- busy: compacting(),
- connected: chat.connectionStatus() === 'connected',
- })
- if (!verdict.ok) throw sendRejection(verdict)
- await chat.sendMessage(content)
- pane.grabStore.clear()
- }
- const onSendError = (failure: unknown) => {
- if (isSendRejection(failure)) {
- if (failure.message) notify(failure.message, {tone: failure.tone === 'warn' ? 'warn' : 'info'})
- return
- }
- notify(failureMessage(failure), {tone: 'danger'})
- }
-
const renderDivider = (row: MarkerRow): JSX.Element =>
const renderTurnPrefix = (turn: Turn): JSX.Element => (
{renderDivider}
@@ -313,8 +272,8 @@ export function ChatPane(props: {sessionId: string}): JSX.Element {
chat.refresh(),
onCancel: () => chat.interruptAndFlush(),
}}
@@ -355,7 +314,7 @@ export function ChatPane(props: {sessionId: string}): JSX.Element {
{(title) => chat.stop()} />}
-
+
{(error) => (
{error().message}
@@ -371,8 +330,6 @@ export function ChatPane(props: {sessionId: string}): JSX.Element {
-
-
{(grab) => (
compact.mutate()}
+ onCompact={() => messaging.compact.mutate()}
onNewSession={() => pane.newSession()}
onStageGrab={stageGrab}
/>
diff --git a/apps/conciv/src/pane/pane-composer.tsx b/apps/conciv/src/pane/pane-composer.tsx
index 2db960c782..70d843e0ba 100644
--- a/apps/conciv/src/pane/pane-composer.tsx
+++ b/apps/conciv/src/pane/pane-composer.tsx
@@ -5,17 +5,10 @@ import Clock from 'lucide-solid/icons/clock'
import Paperclip from 'lucide-solid/icons/paperclip'
import RefreshCw from 'lucide-solid/icons/refresh-cw'
import Square from 'lucide-solid/icons/square'
-import {
- ComposerPrimitive,
- QueueItem,
- AttachmentUI,
- useComposer,
- useComposerContext,
- useComposerHandlers,
- type AttachmentAdapter,
-} from '@conciv/ui-kit-chat'
-import {Swap, TooltipIconButtonSlot} from '@conciv/ui-kit-system'
+import {ComposerPrimitive, QueueItem, AttachmentUI, useComposer, type AttachmentAdapter} from '@conciv/ui-kit-chat'
+import {TooltipIconButtonSlot} from '@conciv/ui-kit-system'
import type {WebStorage} from '@conciv/storage-history'
+import {useEngineReachability} from '../app/reachability.js'
import {
ComposerInputAdapter,
type ComposerInputHandle,
@@ -49,34 +42,28 @@ const QUEUE_ROW =
const QUEUE_ACTION =
'shrink-0 px-2 py-1 rounded-[var(--chat-radius-sm)] bg-transparent [border:none] cursor-pointer font-medium text-[length:var(--chat-text-md)] leading-[1.45] [transition:background-color_120ms_var(--chat-ease),color_120ms_var(--chat-ease),transform_100ms_var(--chat-ease)] hover:[background:var(--chat-fill-strong)] [&:active]:scale-[0.96]'
-function SendOrStopButton(): JSX.Element {
+const ENGINE_UNREACHABLE_LABEL = 'conciv lost connection to the engine'
+
+function ComposerSendControl(): JSX.Element {
const composer = useComposer()
- const context = useComposerContext()
- const handlers = useComposerHandlers()
- const stopping = () => composer.canCancel()
- const cancel = () => (handlers.onCancel ? handlers.onCancel() : composer.cancel())
- const sendDisabled = () => context.sendingAttachments() || (!composer.canSend() && context.attachments().length === 0)
+ const reachability = useEngineReachability()
return (
-
+
+ }
+ >
+
+
+
+
)
}
@@ -90,7 +77,7 @@ function TrailingControls(): JSX.Element {
)}
-
+
>
)
}
diff --git a/apps/conciv/src/pane/send-checks.ts b/apps/conciv/src/pane/send-checks.ts
index 085034ed93..0222f1ce28 100644
--- a/apps/conciv/src/pane/send-checks.ts
+++ b/apps/conciv/src/pane/send-checks.ts
@@ -4,7 +4,7 @@ export const MAX_CONTENT_PARTS = 16
export type SendContent = string | {content: string | ReadonlyArray}
-export type SendState = {busy: boolean; connected: boolean}
+export type SendState = {busy: boolean; connected: boolean; reachable: boolean}
export type SendVerdict = {ok: true} | {ok: false; message: string | null; tone: 'info' | 'warn'}
@@ -25,6 +25,12 @@ export function checkSend(content: SendContent, state: SendState): SendVerdict {
message: 'Message too large to send. Remove an attachment or shorten it.',
tone: 'warn',
}
+ if (!state.reachable)
+ return {
+ ok: false,
+ message: 'conciv lost connection to the engine. Your message is still in the composer.',
+ tone: 'warn',
+ }
if (!state.connected)
return {ok: false, message: 'Not connected yet. Your message is still in the composer.', tone: 'warn'}
return {ok: true}
diff --git a/apps/conciv/src/pane/use-pane-messaging.ts b/apps/conciv/src/pane/use-pane-messaging.ts
new file mode 100644
index 0000000000..d7f0770b56
--- /dev/null
+++ b/apps/conciv/src/pane/use-pane-messaging.ts
@@ -0,0 +1,100 @@
+import {useMutation, type CreateMutationResult} from '@tanstack/solid-query'
+import type {ChatSession} from '@conciv/client'
+import type {RpcClient} from '@conciv/contract'
+import type {MultimodalContent} from '@tanstack/ai-client'
+import type {UiAnswerValue} from '@conciv/protocol/ui-types'
+import type {AppData} from '../data/app-data.js'
+import type {EngineNotices} from '../shell/notice-context.js'
+import {checkSend, type SendVerdict} from './send-checks.js'
+
+type SendRejection = {rejected: true; message: string | null; tone: 'info' | 'warn'}
+
+function sendRejection(verdict: Extract): SendRejection {
+ return {rejected: true, message: verdict.message, tone: verdict.tone}
+}
+
+function isSendRejection(failure: unknown): failure is SendRejection {
+ return typeof failure === 'object' && failure !== null && 'rejected' in failure && failure.rejected === true
+}
+
+function failureMessage(failure: unknown): string {
+ if (failure instanceof Error && failure.message.length > 0) return failure.message
+ return 'The message could not be sent.'
+}
+
+function notifyUnlessOffline(sustainedOffline: boolean, notify: () => void): void {
+ if (sustainedOffline) return
+ notify()
+}
+
+type PaneMessagingDeps = {
+ rpc: RpcClient
+ sessionId: string
+ chat: ChatSession
+ appData: AppData
+ reachability: EngineNotices['reachability']
+ notices: EngineNotices['notices']
+ grabStore: {clear: () => void}
+ refetchMarkers: () => Promise
+}
+
+export type PaneMessaging = {
+ uiReply: CreateMutationResult
+ compact: CreateMutationResult
+ compacting: () => boolean
+ visibleError: () => Error | undefined
+ onSend: (content: string | MultimodalContent) => Promise
+ onSendError: (failure: unknown) => void
+}
+
+export function usePaneMessaging(deps: PaneMessagingDeps): PaneMessaging {
+ const uiReply = useMutation(() => ({
+ mutationFn: (input: {toolCallId: string; value: UiAnswerValue}) =>
+ deps.rpc.chat.uiReply({sessionId: deps.sessionId, toolCallId: input.toolCallId, value: input.value}),
+ onError: () =>
+ notifyUnlessOffline(deps.reachability.sustainedOffline(), () =>
+ deps.notices.notify('That question is no longer waiting for an answer.'),
+ ),
+ }))
+
+ const compact = useMutation(() => ({
+ mutationFn: () => deps.rpc.sessions.compact({sessionId: deps.sessionId}),
+ onError: () =>
+ notifyUnlessOffline(deps.reachability.sustainedOffline(), () =>
+ deps.notices.notify('Compaction failed. The session may be busy. Try again in a moment.'),
+ ),
+ onSettled: () => {
+ deps.appData.invalidateSessions()
+ void deps.refetchMarkers()
+ },
+ }))
+ const compacting = () => compact.isPending
+
+ const visibleError = (): Error | undefined => {
+ const error = deps.reachability.sustainedOffline() ? undefined : deps.chat.error()
+ return error && error.message !== 'stopped' ? error : undefined
+ }
+
+ const onSend = async (content: string | MultimodalContent): Promise => {
+ const verdict = checkSend(content, {
+ busy: compacting(),
+ connected: deps.chat.connectionStatus() === 'connected',
+ reachable: deps.reachability.online(),
+ })
+ if (!verdict.ok) throw sendRejection(verdict)
+ await deps.chat.sendMessage(content)
+ deps.grabStore.clear()
+ }
+
+ const onSendError = (failure: unknown): void => {
+ if (isSendRejection(failure)) {
+ if (failure.message) deps.notices.notify(failure.message, {tone: failure.tone === 'warn' ? 'warn' : 'info'})
+ return
+ }
+ notifyUnlessOffline(deps.reachability.sustainedOffline(), () =>
+ deps.notices.notify(failureMessage(failure), {tone: 'danger'}),
+ )
+ }
+
+ return {uiReply, compact, compacting, visibleError, onSend, onSendError}
+}
diff --git a/apps/conciv/src/routeTree.gen.ts b/apps/conciv/src/routeTree.gen.ts
index 4c3d0baeed..530a855b44 100644
--- a/apps/conciv/src/routeTree.gen.ts
+++ b/apps/conciv/src/routeTree.gen.ts
@@ -13,6 +13,7 @@ import { Route as QuickRouteImport } from './routes/quick'
import { Route as PanelRouteImport } from './routes/panel'
import { Route as IndexRouteImport } from './routes/index'
import { Route as PipSessionIdRouteImport } from './routes/pip.$sessionId'
+import { Route as PanelLatestRouteImport } from './routes/panel.latest'
import { Route as PanelConnectRouteImport } from './routes/panel.connect'
import { Route as PanelSessionIdRouteImport } from './routes/panel.$sessionId'
import { Route as PanelSessionIdIndexRouteImport } from './routes/panel.$sessionId.index'
@@ -38,6 +39,11 @@ const PipSessionIdRoute = PipSessionIdRouteImport.update({
path: '/pip/$sessionId',
getParentRoute: () => rootRouteImport,
} as any)
+const PanelLatestRoute = PanelLatestRouteImport.update({
+ id: '/latest',
+ path: '/latest',
+ getParentRoute: () => PanelRoute,
+} as any)
const PanelConnectRoute = PanelConnectRouteImport.update({
id: '/connect',
path: '/connect',
@@ -65,6 +71,7 @@ export interface FileRoutesByFullPath {
'/quick': typeof QuickRoute
'/panel/$sessionId': typeof PanelSessionIdRouteWithChildren
'/panel/connect': typeof PanelConnectRoute
+ '/panel/latest': typeof PanelLatestRoute
'/pip/$sessionId': typeof PipSessionIdRoute
'/panel/$sessionId/$view': typeof PanelSessionIdViewRoute
'/panel/$sessionId/': typeof PanelSessionIdIndexRoute
@@ -74,6 +81,7 @@ export interface FileRoutesByTo {
'/panel': typeof PanelRouteWithChildren
'/quick': typeof QuickRoute
'/panel/connect': typeof PanelConnectRoute
+ '/panel/latest': typeof PanelLatestRoute
'/pip/$sessionId': typeof PipSessionIdRoute
'/panel/$sessionId/$view': typeof PanelSessionIdViewRoute
'/panel/$sessionId': typeof PanelSessionIdIndexRoute
@@ -85,6 +93,7 @@ export interface FileRoutesById {
'/quick': typeof QuickRoute
'/panel/$sessionId': typeof PanelSessionIdRouteWithChildren
'/panel/connect': typeof PanelConnectRoute
+ '/panel/latest': typeof PanelLatestRoute
'/pip/$sessionId': typeof PipSessionIdRoute
'/panel/$sessionId/$view': typeof PanelSessionIdViewRoute
'/panel/$sessionId/': typeof PanelSessionIdIndexRoute
@@ -97,6 +106,7 @@ export interface FileRouteTypes {
| '/quick'
| '/panel/$sessionId'
| '/panel/connect'
+ | '/panel/latest'
| '/pip/$sessionId'
| '/panel/$sessionId/$view'
| '/panel/$sessionId/'
@@ -106,6 +116,7 @@ export interface FileRouteTypes {
| '/panel'
| '/quick'
| '/panel/connect'
+ | '/panel/latest'
| '/pip/$sessionId'
| '/panel/$sessionId/$view'
| '/panel/$sessionId'
@@ -116,6 +127,7 @@ export interface FileRouteTypes {
| '/quick'
| '/panel/$sessionId'
| '/panel/connect'
+ | '/panel/latest'
| '/pip/$sessionId'
| '/panel/$sessionId/$view'
| '/panel/$sessionId/'
@@ -158,6 +170,13 @@ declare module '@tanstack/solid-router' {
preLoaderRoute: typeof PipSessionIdRouteImport
parentRoute: typeof rootRouteImport
}
+ '/panel/latest': {
+ id: '/panel/latest'
+ path: '/latest'
+ fullPath: '/panel/latest'
+ preLoaderRoute: typeof PanelLatestRouteImport
+ parentRoute: typeof PanelRoute
+ }
'/panel/connect': {
id: '/panel/connect'
path: '/connect'
@@ -206,11 +225,13 @@ const PanelSessionIdRouteWithChildren = PanelSessionIdRoute._addFileChildren(
interface PanelRouteChildren {
PanelSessionIdRoute: typeof PanelSessionIdRouteWithChildren
PanelConnectRoute: typeof PanelConnectRoute
+ PanelLatestRoute: typeof PanelLatestRoute
}
const PanelRouteChildren: PanelRouteChildren = {
PanelSessionIdRoute: PanelSessionIdRouteWithChildren,
PanelConnectRoute: PanelConnectRoute,
+ PanelLatestRoute: PanelLatestRoute,
}
const PanelRouteWithChildren = PanelRoute._addFileChildren(PanelRouteChildren)
diff --git a/apps/conciv/src/router.tsx b/apps/conciv/src/router.tsx
index b0f6eebfa5..c2939e9367 100644
--- a/apps/conciv/src/router.tsx
+++ b/apps/conciv/src/router.tsx
@@ -1,16 +1,18 @@
import {createRouter} from '@tanstack/solid-router'
import type {RouterHistory} from '@tanstack/solid-router'
import {QueryClient} from '@tanstack/solid-query'
-import {onCleanup, type JSX} from 'solid-js'
+import {createEffect, createRoot, onCleanup, type JSX} from 'solid-js'
import type {RpcClient} from '@conciv/contract'
import type {GrabProvider} from '@conciv/grab'
import type {AnyExtension} from '@conciv/extension'
+import {setupEngineReachability} from '@conciv/client'
import {routeTree} from './routeTree.gen'
import {makeAppData, type AppData} from './data/app-data.js'
import type {ConcivSettings} from './data/settings.js'
import type {ExtensionInstance} from './extension/extension-slots.js'
import highlight from './extensions/highlight.js'
import {PendingPane} from './shell/pending.js'
+import {defaultErrorComponent} from './shell/default-error-component.js'
export type ConcivEnvironment = {rootNode: Node; document: Document}
@@ -76,21 +78,40 @@ function disposeExtensionInstances(instances: ExtensionInstance[]): void {
}
}
-function makeGuardedDisposer(instances: ExtensionInstance[]): () => void {
+function makeGuardedDisposer(instances: ExtensionInstance[], extra: () => void): () => void {
let disposed = false
return function disposeInstances(): void {
if (disposed) return
disposed = true
disposeExtensionInstances(instances)
+ extra()
}
}
+function wireEngineReachability(apiBase: () => string): {dispose: () => void} {
+ return createRoot((dispose) => {
+ let wiredApiBase = apiBase()
+ let cleanupReachability = setupEngineReachability(wiredApiBase)
+ createEffect(() => {
+ const nextApiBase = apiBase()
+ if (nextApiBase === wiredApiBase) return
+ cleanupReachability()
+ wiredApiBase = nextApiBase
+ cleanupReachability = setupEngineReachability(nextApiBase)
+ })
+ onCleanup(() => cleanupReachability())
+ return {dispose}
+ })
+}
+
export function createConcivRouter(config: ConcivRouterConfig) {
const queryClient = new QueryClient()
const data = makeAppData(config.rpc, queryClient)
const extensions = [highlight, ...(config.extensions ?? [])]
const instances = createInstances(extensions)
- const disposeInstances = makeGuardedDisposer(instances)
+ const apiBase = config.apiBase ?? (() => '')
+ const reachability = wireEngineReachability(apiBase)
+ const disposeInstances = makeGuardedDisposer(instances, reachability.dispose)
function ConcivRouterWrap(props: {children: JSX.Element}): JSX.Element {
onCleanup(disposeInstances)
return <>{props.children}>
@@ -102,6 +123,7 @@ export function createConcivRouter(config: ConcivRouterConfig) {
defaultPendingComponent: PendingPane,
defaultPendingMs: 300,
defaultPendingMinMs: 500,
+ defaultErrorComponent,
Wrap: ConcivRouterWrap,
context: {
rpc: config.rpc,
@@ -116,7 +138,7 @@ export function createConcivRouter(config: ConcivRouterConfig) {
bindApiBase: config.bindApiBase,
disconnect: config.disconnect,
grabProvider: config.grabProvider,
- apiBase: config.apiBase ?? (() => ''),
+ apiBase,
connectionGeneration: config.connectionGeneration ?? (() => 0),
disposeInstances,
},
diff --git a/apps/conciv/src/routes/__root.tsx b/apps/conciv/src/routes/__root.tsx
index 706ad4800d..9df7e8b0a4 100644
--- a/apps/conciv/src/routes/__root.tsx
+++ b/apps/conciv/src/routes/__root.tsx
@@ -18,14 +18,13 @@ import type {ConcivRouterContext} from '../router.js'
import {
AppContext,
useAppData,
- useAppQueryClient,
useConnected,
useLayers,
- useRpc,
useSettings,
useSuppressed,
type AppContextValue,
} from '../app/context.js'
+import {EngineReachabilityContext, makeEngineReachability} from '../app/reachability.js'
import {makeLayerStack} from '../shell/dialogs.js'
import {ShellFab} from '../shell/fab.js'
import {EffectsSurface} from '../shell/effects-surface.js'
@@ -113,6 +112,7 @@ function RootComponent() {
disconnect: app.disconnect,
grabProvider: app.grabProvider,
connectionGeneration: app.connectionGeneration,
+ apiBase: app.apiBase,
}
createEffect(() => {
@@ -120,23 +120,27 @@ function RootComponent() {
window.dispatchEvent(new CustomEvent('conciv:connection-changed', {detail: {connected: isConnected}}))
})
+ const reachability = makeEngineReachability()
+
return (
app.environment.rootNode}>
- void app.rpc.editor.open({file, line}).catch(() => {})}
- registerLayer={(isOpen, hides) => layers.register(isOpen, hides)}
- dialog={layers.track(Dialog)}
- popover={Object.assign({}, Popover, {Root: layers.track(Popover.Root)})}
- sessionId={activeSession}
- >
-
-
-
+
+ void app.rpc.editor.open({file, line}).catch(() => {})}
+ registerLayer={(isOpen, hides) => layers.register(isOpen, hides)}
+ dialog={layers.track(Dialog)}
+ popover={Object.assign({}, Popover, {Root: layers.track(Popover.Root)})}
+ sessionId={activeSession}
+ >
+
+
+
+
@@ -148,9 +152,7 @@ function RootChrome(props: {
politeMessage: () => string
assertiveMessage: () => string
}) {
- const rpc = useRpc()
const data = useAppData()
- const queryClient = useAppQueryClient()
const settings = useSettings()
const layers = useLayers()
const suppressed = useSuppressed()
@@ -179,22 +181,11 @@ function RootChrome(props: {
enabled: connected() && Boolean(latestSessionRow()),
}))
- const [openIntent, setOpenIntent] = createSignal(false)
-
let rootEl: HTMLDivElement | undefined
let fabEl: HTMLButtonElement | undefined
let pendingFabFocus = false
let hostRestoreTarget: HTMLElement | null = null
- const latestSessionId = async (): Promise => {
- try {
- const rows = await queryClient.ensureQueryData(data.utils.sessions.list.queryOptions())
- const latest = rows.toSorted((a, b) => b.updatedAt - a.updatedAt)[0]
- return (await rpc.sessions.resolve(latest ? {id: latest.id} : {})).sessionId
- } catch {
- return null
- }
- }
const mascotRect = (): {x: number; y: number; width: number; height: number} | null => {
if (settings.launcher !== 'mascot') return null
const rect = fabEl?.getBoundingClientRect()
@@ -208,26 +199,25 @@ function RootChrome(props: {
}),
)
}
- const openPanel = async () => {
+ const openPanel = () => {
if (!panelOpen()) hostRestoreTarget = rootEl ? hostFocusTarget(rootEl) : null
if (panelMatch() || connectMatch()) {
- setOpenIntent(true)
void setShutter(router, true)
return
}
- setOpenIntent(true)
- const sessionId = warmSession.data?.sessionId ?? (await latestSessionId())
- if (!sessionId) return
- if (!openIntent()) return
- void router.navigate({
- to: '/panel/$sessionId',
- params: {sessionId},
- search: {open: true},
- replace: Boolean(quickMatch()),
- })
+ const sessionId = warmSession.data?.sessionId
+ if (sessionId) {
+ void router.navigate({
+ to: '/panel/$sessionId',
+ params: {sessionId},
+ search: {open: true},
+ replace: Boolean(quickMatch()),
+ })
+ return
+ }
+ void router.navigate({to: '/panel/latest', search: {open: true}, replace: Boolean(quickMatch())})
}
const closePanel = () => {
- setOpenIntent(false)
const captured = hostRestoreTarget
hostRestoreTarget = null
void setShutter(router, false).then(() => {
@@ -273,11 +263,7 @@ function RootChrome(props: {
if (settings.defaultOpen && closedMatch()) void openPanel()
const openFromHost = () => void openPanel()
const closeFromHost = () => {
- if (panelOpen()) {
- closePanel()
- return
- }
- setOpenIntent(false)
+ if (panelOpen()) closePanel()
}
const toggleFromHost = () => togglePanel()
makeEventListener(window, 'resize', reportPanelState)
diff --git a/apps/conciv/src/routes/panel.connect.tsx b/apps/conciv/src/routes/panel.connect.tsx
index 1458799b4b..9553c9e22a 100644
--- a/apps/conciv/src/routes/panel.connect.tsx
+++ b/apps/conciv/src/routes/panel.connect.tsx
@@ -1,8 +1,15 @@
import {HostApiProvider} from '@conciv/extension'
import {createFileRoute, useRouter} from '@tanstack/solid-router'
-import type {JSX} from 'solid-js'
+import {useMutation} from '@tanstack/solid-query'
+import {reprobeBrowserRpcConnection} from '@conciv/contract'
+import {Show, type JSX} from 'solid-js'
import {useConnectBinding, useInstances} from '../app/context.js'
import {ExtensionSurface} from '../extension/extension-slots.js'
+import {ErrorScreen} from '../shell/error-screen.js'
+import {classifyRpcError} from '../shell/rpc-error-message.js'
+
+const BIND_FAILED_MESSAGE = "conciv couldn't connect to that workspace. Check that the dev server is still running."
+const GENERIC_ERROR_MESSAGE = 'Something went wrong connecting to that workspace. Try again.'
export const Route = createFileRoute('/panel/connect')({component: ConnectRoute})
@@ -10,17 +17,33 @@ function ConnectRoute(): JSX.Element {
const instances = useInstances()
const binding = useConnectBinding()
const router = useRouter()
- const found = (apiBase: string) => {
- void binding
- .bind(apiBase)
- .then((sessionId) =>
- router.navigate({to: '/panel/$sessionId', params: {sessionId}, search: {open: true}, replace: true}),
- )
- .catch((error) => console.error('conciv connect handoff failed', error))
+
+ const bind = useMutation(() => ({
+ mutationFn: (apiBase: string) => binding.bind(apiBase),
+ onSuccess: (sessionId) =>
+ router.navigate({to: '/panel/$sessionId', params: {sessionId}, search: {open: true}, replace: true}),
+ }))
+
+ const retry = (apiBase: string): void => {
+ if (classifyRpcError(bind.error, BIND_FAILED_MESSAGE, GENERIC_ERROR_MESSAGE).transportFailure)
+ reprobeBrowserRpcConnection(apiBase)
+ bind.mutate(apiBase)
}
+
return (
-
-
+ bind.mutate(apiBase)}}>
+ }
+ keyed
+ >
+ {(apiBase) => (
+ retry(apiBase)}
+ />
+ )}
+
)
}
diff --git a/apps/conciv/src/routes/panel.latest.tsx b/apps/conciv/src/routes/panel.latest.tsx
new file mode 100644
index 0000000000..857baa7845
--- /dev/null
+++ b/apps/conciv/src/routes/panel.latest.tsx
@@ -0,0 +1,8 @@
+import {createFileRoute, redirect} from '@tanstack/solid-router'
+
+export const Route = createFileRoute('/panel/latest')({
+ beforeLoad: async ({context}) => {
+ const {sessionId} = await context.rpc.sessions.resolve({})
+ throw redirect({to: '/panel/$sessionId', params: {sessionId}, replace: true})
+ },
+})
diff --git a/apps/conciv/src/routes/panel.tsx b/apps/conciv/src/routes/panel.tsx
index 743f2c6f7c..bbea655fb1 100644
--- a/apps/conciv/src/routes/panel.tsx
+++ b/apps/conciv/src/routes/panel.tsx
@@ -6,6 +6,8 @@ import {useFabPosition, useLayers, useSuppressed} from '../app/context.js'
import {makePanelComposerFocus, PanelComposerFocusContext} from '../app/panel-focus.js'
import {usePanelChrome} from '../app/panel-chrome.js'
import {createMediaQuery, PHONE_MEDIA_QUERY} from '../lib/media-query.js'
+import {NoticeContextProvider, NoticeSurface} from '../shell/notice-context.js'
+import {EngineStaleNotice, EngineUnreachableNotice} from '../shell/engine-notice.js'
const PANEL_POS: Record = {
'top-left': 'top-21 left-5 [transform-origin:top_left]',
@@ -71,49 +73,54 @@ function PanelLayout(): JSX.Element {
return (
-
-
-
-
-
+
+
+
+
)
}
diff --git a/apps/conciv/src/routes/pip.$sessionId.tsx b/apps/conciv/src/routes/pip.$sessionId.tsx
index 2bccb119ea..8b86f3437c 100644
--- a/apps/conciv/src/routes/pip.$sessionId.tsx
+++ b/apps/conciv/src/routes/pip.$sessionId.tsx
@@ -6,6 +6,8 @@ import {EnvironmentProvider} from '@conciv/ui-kit-system'
import {PaneProvider} from '../app/pane-provider.js'
import {ChatPane} from '../pane/chat-pane.js'
import {openPipWindow, type PipWindow} from '../shell/pip.js'
+import {NoticeContextProvider, NoticeSurface} from '../shell/notice-context.js'
+import {EngineStaleNotice, EngineUnreachableNotice} from '../shell/engine-notice.js'
export const Route = createFileRoute('/pip/$sessionId')({component: PipSession})
@@ -33,15 +35,20 @@ function PipSession(): JSX.Element {
{(target) => (
target.root}>
-
- {(sessionId) => (
-
-
-
-
-
- )}
-
+
+
+ {(sessionId) => (
+
+
+
+
+
+
+
+
+ )}
+
+
)}
diff --git a/apps/conciv/src/routes/quick.tsx b/apps/conciv/src/routes/quick.tsx
index 754c38380d..40d93f11a0 100644
--- a/apps/conciv/src/routes/quick.tsx
+++ b/apps/conciv/src/routes/quick.tsx
@@ -1,18 +1,21 @@
import {createFileRoute, redirect, useRouter} from '@tanstack/solid-router'
-import {useQuery} from '@tanstack/solid-query'
+import {useQuery, useMutation} from '@tanstack/solid-query'
import {createHotkey} from '@tanstack/solid-hotkeys'
-import {For, Show, Suspense, onCleanup, onMount, type JSX} from 'solid-js'
-import {TooltipIconButton, createResizable} from '@conciv/ui-kit-system'
+import {For, Show, Suspense, createEffect, onCleanup, onMount, type JSX} from 'solid-js'
+import {Button, TooltipIconButton, createResizable} from '@conciv/ui-kit-system'
import ChevronUp from 'lucide-solid/icons/chevron-up'
import Columns2 from 'lucide-solid/icons/columns-2'
import PictureInPicture2 from 'lucide-solid/icons/picture-in-picture-2'
import X from 'lucide-solid/icons/x'
import {useAppData, useRpc, useSuppressed} from '../app/context.js'
+import {useEngineReachability} from '../app/reachability.js'
import {PaneProvider} from '../app/pane-provider.js'
import {ChatPane} from '../pane/chat-pane.js'
import {ContextTracker} from '../pane/context-tracker.js'
import {SessionSelector} from '../composer/session-selector.js'
import {SessionPillPending, UsagePending} from '../shell/pending.js'
+import {NoticeContextProvider, NoticeSurface} from '../shell/notice-context.js'
+import {EngineStaleNotice, EngineUnreachableNotice} from '../shell/engine-notice.js'
import {QuickSearchSchema, quickPaneIds, quickSearchFor} from '../lib/quick-search.js'
const CLOSE =
@@ -20,6 +23,8 @@ const CLOSE =
const CLOSE_PANE = 'text-pw-text-3 leading-none ml-auto size-6'
+const ADD_PANE_FAILED_MESSAGE = 'conciv could not start a pane. Check the engine connection and retry.'
+
export const Route = createFileRoute('/quick')({
validateSearch: QuickSearchSchema,
beforeLoad: ({context}) => {
@@ -100,17 +105,33 @@ function QuickLayer(): JSX.Element {
let rowEl: HTMLDivElement | undefined
+ const reachability = useEngineReachability()
+
const setSearch = (ids: string[], focus: number) =>
void router.navigate({to: '/quick', search: quickSearchFor(ids, focus), replace: true})
- const addPane = async () => {
- const {sessionId} = await rpc.sessions.resolve({})
- const ids = [...paneIds(), sessionId]
- setSearch(ids, ids.length - 1)
- appData.invalidateSessions()
- resetPaneFlex(rowEl)
+ const addPane = useMutation(() => ({
+ mutationFn: () => rpc.sessions.resolve({}),
+ onSuccess: ({sessionId}) => {
+ const ids = [...paneIds(), sessionId]
+ setSearch(ids, ids.length - 1)
+ appData.invalidateSessions()
+ resetPaneFlex(rowEl)
+ },
+ }))
+
+ const triggerAddPane = (): void => {
+ if (addPane.isPending) return
+ addPane.mutate()
}
+ let wasOnline = reachability.online()
+ createEffect(() => {
+ const isOnline = reachability.online()
+ if (isOnline && !wasOnline && paneIds().length === 0) triggerAddPane()
+ wasOnline = isOnline
+ })
+
const closePane = (index: number) => {
const ids = paneIds()
const closed = ids[index]
@@ -144,102 +165,124 @@ function QuickLayer(): JSX.Element {
onCollapse: () => router.history.back(),
})
- createHotkey({key: 'D', mod: true}, () => void addPane())
+ createHotkey({key: 'D', mod: true}, () => triggerAddPane())
let restoreFocus: HTMLElement | null = null
onMount(() => {
restoreFocus = document.activeElement instanceof HTMLElement ? document.activeElement : null
- if (paneIds().length === 0) void addPane()
+ if (paneIds().length === 0) triggerAddPane()
})
onCleanup(() => restoreFocus?.focus())
return (
-
- {
- const id = paneIds()[focusedIndex()]
- if (id) void router.navigate({to: '/pip/$sessionId', params: {sessionId: id}})
- }}
- onSplit={() => void addPane()}
- onClose={() => router.history.back()}
- />
- {
- rowEl = el
- }}
+
+
-
- {(id, index) => (
- <>
- 0}>
-
-
+
+
+
+ {
+ const id = paneIds()[focusedIndex()]
+ if (id) void router.navigate({to: '/pip/$sessionId', params: {sessionId: id}})
+ }}
+ onSplit={() => triggerAddPane()}
+ onClose={() => router.history.back()}
+ />
+ {
+ rowEl = el
+ }}
+ >
+
0}
+ fallback={
focusPane(index())}
- onFocusIn={() => {
- if (focusedIndex() !== index()) focusPane(index())
- }}
+ class="flex flex-1 flex-col items-center justify-center gap-2 p-6 text-center text-pw-text-2 text-[0.8125rem]"
+ role="status"
>
-
-
}>
-
id}
- onActivate={(next) => activatePane(index(), next)}
- onNewSession={() => void addPane()}
+ {addPane.isError ? ADD_PANE_FAILED_MESSAGE : 'Starting a paneā¦'}
+
+
+
+
+ }
+ >
+
+ {(id, index) => (
+ <>
+ 0}>
+
-
- }>
-
-
- {
- e.stopPropagation()
- closePane(index())
+
+ focusPane(index())}
+ onFocusIn={() => {
+ if (focusedIndex() !== index()) focusPane(index())
}}
>
-
-
-
-
- {(sessionId) => (
- void addPane()}>
-
-
- )}
-
-
- >
- )}
-
-
-
-
+
+ }>
+ id}
+ onActivate={(next) => activatePane(index(), next)}
+ onNewSession={triggerAddPane}
+ />
+
+ }>
+
+
+ {
+ e.stopPropagation()
+ closePane(index())
+ }}
+ >
+
+
+
+
+ {(sessionId) => (
+
+
+
+ )}
+
+
+ >
+ )}
+
+
+
+
+
+
)
}
diff --git a/apps/conciv/src/shell/default-error-component.tsx b/apps/conciv/src/shell/default-error-component.tsx
new file mode 100644
index 0000000000..ed82f751cb
--- /dev/null
+++ b/apps/conciv/src/shell/default-error-component.tsx
@@ -0,0 +1,21 @@
+import {createMemo, type JSX} from 'solid-js'
+import {useRouteContext, useRouter, type ErrorComponentProps} from '@tanstack/solid-router'
+import {reprobeBrowserRpcConnection} from '@conciv/contract'
+import {ErrorScreen} from './error-screen.js'
+import {classifyRpcError, type RpcErrorClassification} from './rpc-error-message.js'
+
+const ENGINE_UNREACHABLE_MESSAGE = "conciv couldn't reach the engine. Check that the dev server is still running."
+const GENERIC_ERROR_MESSAGE = 'Something went wrong. Try again.'
+
+export function defaultErrorComponent(props: ErrorComponentProps): JSX.Element {
+ const router = useRouter()
+ const apiBase = useRouteContext({strict: false, select: (context) => context.apiBase})
+ const classification = createMemo(() =>
+ classifyRpcError(props.error, ENGINE_UNREACHABLE_MESSAGE, GENERIC_ERROR_MESSAGE),
+ )
+ const retry = (): void => {
+ if (classification().transportFailure) reprobeBrowserRpcConnection(apiBase()?.() ?? '')
+ void router.invalidate()
+ }
+ return
+}
diff --git a/apps/conciv/src/shell/engine-notice.tsx b/apps/conciv/src/shell/engine-notice.tsx
index d27dbb0a1c..58e722154e 100644
--- a/apps/conciv/src/shell/engine-notice.tsx
+++ b/apps/conciv/src/shell/engine-notice.tsx
@@ -1,21 +1,42 @@
import {createEffect, type JSX} from 'solid-js'
import {useQuery} from '@tanstack/solid-query'
-import {useAppData, useConnected} from '../app/context.js'
-import {notify, toaster} from './notices.js'
+import {useRouter} from '@tanstack/solid-router'
+import {engineProbeRefetchInterval, voteEngineProbeSettled} from '@conciv/client'
+import {reprobeBrowserRpcConnection} from '@conciv/contract'
+import {useApiBase, useAppData, useConnected} from '../app/context.js'
+import {useEngineReachability} from '../app/reachability.js'
+import {useNotices} from './notice-context.js'
const ENGINE_STALE_MESSAGE =
'Engine is running outdated code: the server code on disk is newer than the running engine. Restart the dev server.'
+const ENGINE_UNREACHABLE_KEY = 'engine-unreachable'
+const ENGINE_UNREACHABLE_MESSAGE = 'conciv lost connection to the engine.'
+
export function EngineStaleNotice(): JSX.Element {
const appData = useAppData()
const connected = useConnected()
- const engine = useQuery(() => ({...appData.utils.meta.engine.queryOptions(), enabled: connected()}))
+ const reachability = useEngineReachability()
+ const notices = useNotices()
+ const engine = useQuery(() => ({
+ ...appData.utils.meta.engine.queryOptions(),
+ enabled: connected(),
+ networkMode: 'always',
+ refetchInterval: engineProbeRefetchInterval(reachability.online()),
+ }))
const standing = {fingerprint: null as string | null}
const clear = (): void => {
if (standing.fingerprint === null) return
- toaster.remove(standing.fingerprint)
+ notices.remove(standing.fingerprint)
standing.fingerprint = null
}
+ const lastSettle = {at: 0}
+ createEffect(() => {
+ const settledAt = engine.dataUpdatedAt
+ if (settledAt === lastSettle.at) return
+ lastSettle.at = settledAt
+ voteEngineProbeSettled(engine.isSuccess, engine.error)
+ })
createEffect(() => {
const reading = engine.data
if (reading === undefined) return
@@ -26,7 +47,31 @@ export function EngineStaleNotice(): JSX.Element {
if (standing.fingerprint === reading.fingerprint) return
clear()
standing.fingerprint = reading.fingerprint
- notify(ENGINE_STALE_MESSAGE, {key: reading.fingerprint, tone: 'danger', persist: true})
+ notices.notify(ENGINE_STALE_MESSAGE, {key: reading.fingerprint, tone: 'danger', persist: true})
+ })
+ return null
+}
+
+export function EngineUnreachableNotice(): JSX.Element {
+ const reachability = useEngineReachability()
+ const notices = useNotices()
+ const apiBase = useApiBase()
+ const router = useRouter()
+ const retry = (): void => {
+ reprobeBrowserRpcConnection(apiBase())
+ void router.invalidate()
+ }
+ createEffect(() => {
+ if (!reachability.sustainedOffline()) {
+ notices.remove(ENGINE_UNREACHABLE_KEY)
+ return
+ }
+ notices.notify(ENGINE_UNREACHABLE_MESSAGE, {
+ key: ENGINE_UNREACHABLE_KEY,
+ tone: 'danger',
+ persist: true,
+ action: {label: 'Retry', run: retry},
+ })
})
return null
}
diff --git a/apps/conciv/src/shell/error-screen.tsx b/apps/conciv/src/shell/error-screen.tsx
new file mode 100644
index 0000000000..0e3fa3b9ff
--- /dev/null
+++ b/apps/conciv/src/shell/error-screen.tsx
@@ -0,0 +1,24 @@
+import type {JSX} from 'solid-js'
+import AlertTriangle from 'lucide-solid/icons/alert-triangle'
+import {Button} from '@conciv/ui-kit-system'
+
+export type ErrorScreenProps = {
+ message: string
+ onRetry: () => void
+}
+
+export function ErrorScreen(props: ErrorScreenProps): JSX.Element {
+ return (
+
+
+
{props.message}
+
+
+ )
+}
diff --git a/apps/conciv/src/shell/notice-context.tsx b/apps/conciv/src/shell/notice-context.tsx
new file mode 100644
index 0000000000..72160fe5d5
--- /dev/null
+++ b/apps/conciv/src/shell/notice-context.tsx
@@ -0,0 +1,27 @@
+import {createContext, useContext, type JSX} from 'solid-js'
+import {useEngineReachability, type EngineReachability} from '../app/reachability.js'
+import {createNoticeStore, type NoticeStore} from './notices.js'
+
+const NoticeStoreContext = createContext()
+
+export function NoticeContextProvider(props: {children: JSX.Element}): JSX.Element {
+ const store = createNoticeStore()
+ return {props.children}
+}
+
+export function useNotices(): NoticeStore {
+ const value = useContext(NoticeStoreContext)
+ if (!value) throw new Error('useNotices called outside NoticeContextProvider')
+ return value
+}
+
+export function NoticeSurface(): JSX.Element {
+ const store = useNotices()
+ return store.Toaster()
+}
+
+export type EngineNotices = {reachability: EngineReachability; notices: NoticeStore}
+
+export function useEngineNotices(): EngineNotices {
+ return {reachability: useEngineReachability(), notices: useNotices()}
+}
diff --git a/apps/conciv/src/shell/notices.tsx b/apps/conciv/src/shell/notices.tsx
index b811e883b6..acac2efd61 100644
--- a/apps/conciv/src/shell/notices.tsx
+++ b/apps/conciv/src/shell/notices.tsx
@@ -10,8 +10,14 @@ export type NoticeOptions = {key?: string; tone?: NoticeTone; action?: NoticeAct
export type Notify = (message: string, options?: NoticeOptions) => void
+export type NoticeStore = {
+ notify: Notify
+ remove: (key: string) => void
+ Toaster: () => JSX.Element
+}
+
const FUSE_MS = 6_000
-const STANDING_LIMIT = 2
+const STANDING_LIMIT = 3
const TOAST_TYPE: Record = {info: 'info', success: 'success', warn: 'warning', danger: 'error'}
@@ -32,50 +38,56 @@ function toneClass(type: string | undefined): string {
return TONE_INFO
}
-export const toaster = createToaster({placement: 'bottom', gap: 8, max: STANDING_LIMIT, offsets: '1rem'})
+export function createNoticeStore(): NoticeStore {
+ const toaster = createToaster({placement: 'bottom', gap: 8, max: STANDING_LIMIT})
-export const notify: Notify = (message, options = {}) => {
- const action = options.action
- const standing = options.persist === true || action !== undefined
- toaster.create({
- ...(options.key ? {id: options.key} : {}),
- ...(action ? {action: {label: action.label, onClick: action.run}} : {}),
- title: message,
- type: TOAST_TYPE[options.tone ?? 'info'],
- duration: standing ? Number.POSITIVE_INFINITY : FUSE_MS,
- })
-}
+ const notify: Notify = (message, options = {}) => {
+ const action = options.action
+ const standing = options.persist === true || action !== undefined
+ toaster.create({
+ ...(options.key ? {id: options.key} : {}),
+ ...(action ? {action: {label: action.label, onClick: action.run}} : {}),
+ title: message,
+ type: TOAST_TYPE[options.tone ?? 'info'],
+ duration: standing ? Number.POSITIVE_INFINITY : FUSE_MS,
+ })
+ }
+
+ const remove = (key: string): void => toaster.remove(key)
+
+ function Toaster(): JSX.Element {
+ return (
+
+ {(toast) => (
+
+ {toast().title}
+
+ {(action) => (
+ (
+
+ )}
+ />
+ )}
+
+ (
+
+
+
+ )}
+ />
+
+ )}
+
+ )
+ }
-export function NoticeToaster(): JSX.Element {
- return (
-
- {(toast) => (
-
- {toast().title}
-
- {(action) => (
- (
-
- )}
- />
- )}
-
- (
-
-
-
- )}
- />
-
- )}
-
- )
+ return {notify, remove, Toaster}
}
diff --git a/apps/conciv/src/shell/rpc-error-message.ts b/apps/conciv/src/shell/rpc-error-message.ts
new file mode 100644
index 0000000000..0e3d84978b
--- /dev/null
+++ b/apps/conciv/src/shell/rpc-error-message.ts
@@ -0,0 +1,17 @@
+import {isReachabilityError} from '@conciv/client'
+
+export type RpcErrorClassification = {
+ message: string
+ transportFailure: boolean
+}
+
+export function classifyRpcError(
+ error: unknown,
+ transportMessage: string,
+ genericMessage: string,
+): RpcErrorClassification {
+ const transportFailure = isReachabilityError(error)
+ if (transportFailure) return {message: transportMessage, transportFailure}
+ const message = error instanceof Error && error.message.length > 0 ? error.message : genericMessage
+ return {message, transportFailure}
+}
diff --git a/apps/conciv/test/engine-staleness.browser.test.tsx b/apps/conciv/test/engine-staleness.browser.test.tsx
index 28cf0e42dc..c348bb74de 100644
--- a/apps/conciv/test/engine-staleness.browser.test.tsx
+++ b/apps/conciv/test/engine-staleness.browser.test.tsx
@@ -3,26 +3,19 @@ import './helpers/utilities.css'
import {afterEach, expect, test} from 'vitest'
import {page} from 'vitest/browser'
import {EngineStaleNotice} from '../src/shell/engine-notice.js'
-import {NoticeToaster, toaster} from '../src/shell/notices.js'
import {installFakeCore, sessionRow, type FakeCore} from './helpers/fake-core.js'
import {mountPane, PANE_SESSION} from './helpers/pane-harness.js'
let core: FakeCore | null = null
afterEach(() => {
- toaster.remove()
core?.restore()
core = null
})
function mountNotice(config: Parameters[0] = {}): {refetch: () => Promise} {
core = installFakeCore({sessions: [sessionRow({id: PANE_SESSION})], ...config})
- const mounted = mountPane(() => (
- <>
-
-
- >
- ))
+ const mounted = mountPane(() => )
return {refetch: mounted.refetch}
}
diff --git a/apps/conciv/test/helpers/fake-core.ts b/apps/conciv/test/helpers/fake-core.ts
index 0370ffc34b..5c45638d0a 100644
--- a/apps/conciv/test/helpers/fake-core.ts
+++ b/apps/conciv/test/helpers/fake-core.ts
@@ -1,3 +1,4 @@
+import {onlineManager} from '@tanstack/query-core'
import {
browserRpcConnection,
closeBrowserRpcConnection,
@@ -19,6 +20,10 @@ export type FakeCore = {
idle: () => Promise
restore: () => void
setEngine: (next: {stale: boolean; fingerprint?: string}) => void
+ setNetworkFail: (fail: boolean) => void
+ setResolveRejects: (fail: boolean) => void
+ setRejectEngineProbe: (fail: boolean) => void
+ setResolveTransportFails: (fail: boolean) => void
}
const QUIET_MS = 60
@@ -35,6 +40,10 @@ export type FakeCoreConfig = {
launchOk?: boolean
launchRejects?: boolean
engineStale?: boolean
+ networkFail?: boolean
+ resolveRejects?: boolean
+ rejectEngineProbe?: boolean
+ resolveTransportFails?: boolean
}
export function sessionRow(overrides: Partial & {id: string}): SessionMeta {
@@ -87,6 +96,10 @@ export function installFakeCore(config: FakeCoreConfig = {}): FakeCore {
const calls: CoreCall[] = []
let subscribes = 0
let snapshotReleased = false
+ let networkFail = config.networkFail ?? false
+ let resolveRejects = config.resolveRejects ?? false
+ let rejectEngineProbe = config.rejectEngineProbe ?? false
+ let resolveTransportFails = config.resolveTransportFails ?? false
if (typeof window !== 'undefined') window.__CONCIV_API_BASE__ = CORE_BASE
let inFlight = 0
let quietTimer: ReturnType | undefined
@@ -113,12 +126,25 @@ export function installFakeCore(config: FakeCoreConfig = {}): FakeCore {
restore: () => {
globalThis.fetch = realFetch
closeBrowserRpcConnection(CORE_BASE)
+ onlineManager.setOnline(true)
if (typeof window !== 'undefined') delete window.__CONCIV_API_BASE__
},
setEngine: (next) => {
engine.stale = next.stale
if (next.fingerprint !== undefined) engine.fingerprint = next.fingerprint
},
+ setNetworkFail: (fail) => {
+ networkFail = fail
+ },
+ setResolveRejects: (fail) => {
+ resolveRejects = fail
+ },
+ setRejectEngineProbe: (fail) => {
+ rejectEngineProbe = fail
+ },
+ setResolveTransportFails: (fail) => {
+ resolveTransportFails = fail
+ },
}
const liveStream = (signal: AbortSignal): Response => {
@@ -142,7 +168,12 @@ export function installFakeCore(config: FakeCoreConfig = {}): FakeCore {
const routes: Record Response> = {
'/rpc/sessions/list': () => reply(config.sessions ?? [sessionRow({id: 'conciv_1'})]),
- '/rpc/sessions/resolve': () => reply({sessionId: config.sessions?.[0]?.id ?? 'conciv_1'}),
+ '/rpc/sessions/resolve': () => {
+ if (resolveTransportFails) throw new TypeError('Failed to fetch')
+ return resolveRejects
+ ? new Response('resolve refused', {status: 500})
+ : reply({sessionId: config.sessions?.[0]?.id ?? 'conciv_1'})
+ },
'/rpc/sessions/create': () => reply({sessionId: 'conciv_2'}),
'/rpc/sessions/compact': () => reply({ok: true}),
'/rpc/drafts/get': () => reply(config.draft ?? null),
@@ -157,14 +188,17 @@ export function installFakeCore(config: FakeCoreConfig = {}): FakeCore {
}),
'/rpc/meta/commands': () => reply({commands: []}),
'/rpc/meta/engine': () =>
- reply({
- stale: engine.stale,
- changed: engine.stale ? ['@conciv/tools'] : [],
- tracked: ['@conciv/core', '@conciv/tools'],
- bootedAt: 0,
- fingerprint: engine.fingerprint,
- }),
+ rejectEngineProbe
+ ? new Response('engine probe refused', {status: 500})
+ : reply({
+ stale: engine.stale,
+ changed: engine.stale ? ['@conciv/tools'] : [],
+ tracked: ['@conciv/core', '@conciv/tools'],
+ bootedAt: 0,
+ fingerprint: engine.fingerprint,
+ }),
'/rpc/meta/tools': () => reply({tools: []}),
+ '/rpc/registry/catalog': () => reply([]),
'/rpc/chat/subscribe': (_body, signal) => liveStream(signal),
'/rpc/chat/stop': () => reply({ok: true}),
'/rpc/chat/send': () => {
@@ -187,6 +221,7 @@ export function installFakeCore(config: FakeCoreConfig = {}): FakeCore {
const request = input instanceof Request ? input : new Request(input, init)
const url = new URL(request.url)
if (url.origin !== CORE_BASE) return realFetch(input, init)
+ if (networkFail) throw new TypeError('Failed to fetch')
const route = routes[url.pathname]
if (!route) throw new Error(`the fake core has no route for ${url.pathname}`)
inFlight += 1
diff --git a/apps/conciv/test/helpers/pane-harness.tsx b/apps/conciv/test/helpers/pane-harness.tsx
index 2f5f72a3b1..830a47359d 100644
--- a/apps/conciv/test/helpers/pane-harness.tsx
+++ b/apps/conciv/test/helpers/pane-harness.tsx
@@ -1,9 +1,10 @@
-import {createSignal, type JSX} from 'solid-js'
+import {createRoot, createSignal, type JSX} from 'solid-js'
import {render} from '@solidjs/testing-library'
import {QueryClient, QueryClientProvider} from '@tanstack/solid-query'
import {makeRpcClient} from '@conciv/contract'
import {HostApiProvider} from '@conciv/extension'
import {AppContext, type AppContextValue} from '../../src/app/context.js'
+import {EngineReachabilityContext, makeEngineReachability} from '../../src/app/reachability.js'
import {
PaneContext,
makeGrabStore,
@@ -13,6 +14,7 @@ import {
import {makeAppData} from '../../src/data/app-data.js'
import {parseConcivSettings} from '../../src/data/settings.js'
import {makeLayerStack} from '../../src/shell/dialogs.js'
+import {NoticeContextProvider, NoticeSurface} from '../../src/shell/notice-context.js'
import {CORE_BASE} from './fake-core.js'
export const PANE_SESSION = 'conciv_1'
@@ -53,6 +55,7 @@ export function mountPane(view: (pane: PaneContextValue) => JSX.Element): PaneMo
connectBind: async () => '',
connectMode: false,
connectionGeneration: () => 0,
+ apiBase: () => CORE_BASE,
}
const pane: PaneContextValue = {
sessionId: () => PANE_SESSION,
@@ -66,20 +69,34 @@ export function mountPane(view: (pane: PaneContextValue) => JSX.Element): PaneMo
attachments: makePendingAttachmentQueue(),
newSession: () => {},
}
+ const reachabilityRoot = createRoot((disposeReachability) => ({
+ reachability: makeEngineReachability(),
+ dispose: disposeReachability,
+ }))
const mounted = render(() => (
-
- ''} toast={(message) => app.announce(message)}>
- {view(pane)}
-
-
-
+
+
+
+ ''} toast={(message) => app.announce(message)}>
+
+ {view(pane)}
+
+
+
+
+
+
+
))
return {
- dispose: mounted.unmount,
+ dispose: () => {
+ mounted.unmount()
+ reachabilityRoot.dispose()
+ },
announced,
pane,
refetch: () => queryClient.invalidateQueries({queryKey: data.utils.meta.engine.key()}),
diff --git a/apps/conciv/test/helpers/retry-recovery.ts b/apps/conciv/test/helpers/retry-recovery.ts
new file mode 100644
index 0000000000..c9a0b9ec7b
--- /dev/null
+++ b/apps/conciv/test/helpers/retry-recovery.ts
@@ -0,0 +1,15 @@
+import {expect} from 'vitest'
+import {page} from 'vitest/browser'
+
+type Locator = ReturnType
+
+export async function expectRetryRecovers(
+ clearFailure: () => void,
+ editor: () => Locator,
+ failureLocator: () => Locator,
+): Promise {
+ clearFailure()
+ await page.getByRole('button', {name: 'Retry'}).click()
+ await expect.element(editor(), {timeout: 8000}).toBeVisible()
+ await expect.element(failureLocator()).not.toBeInTheDocument()
+}
diff --git a/apps/conciv/test/helpers/shell-harness.tsx b/apps/conciv/test/helpers/shell-harness.tsx
new file mode 100644
index 0000000000..b65a57347c
--- /dev/null
+++ b/apps/conciv/test/helpers/shell-harness.tsx
@@ -0,0 +1,41 @@
+import {render} from '@solidjs/testing-library'
+import {RouterProvider, createMemoryHistory} from '@tanstack/solid-router'
+import {makeBrowserRpcClient} from '@conciv/contract'
+import type {AnyExtension} from '@conciv/extension'
+import {parseConcivSettings} from '../../src/data/settings.js'
+import {createConcivRouter, disposeConcivRouter} from '../../src/router.js'
+import {CORE_BASE, installFakeCore, sessionRow, type FakeCore, type FakeCoreConfig} from './fake-core.js'
+
+export type ShellHarness = {
+ mountShell: (entry: string, config?: FakeCoreConfig, extensions?: AnyExtension[]) => void
+ core: () => FakeCore | null
+ dispose: () => void
+}
+
+export function createShellHarness(sessionId: string): ShellHarness {
+ let core: FakeCore | null = null
+ let mountedRouter: ReturnType | null = null
+
+ const mountShell = (entry: string, config: FakeCoreConfig = {}, extensions: AnyExtension[] = []): void => {
+ core = installFakeCore({sessions: [sessionRow({id: sessionId})], ...config})
+ const router = createConcivRouter({
+ rpc: makeBrowserRpcClient(CORE_BASE, {transport: 'fetch'}).rpc,
+ history: createMemoryHistory({initialEntries: [entry]}),
+ environment: {rootNode: document, document},
+ settings: parseConcivSettings(''),
+ apiBase: () => CORE_BASE,
+ extensions,
+ })
+ mountedRouter = router
+ render(() => )
+ }
+
+ const dispose = (): void => {
+ if (mountedRouter) disposeConcivRouter(mountedRouter)
+ mountedRouter = null
+ core?.restore()
+ core = null
+ }
+
+ return {mountShell, core: () => core, dispose}
+}
diff --git a/apps/conciv/test/kit-controls.browser.test.tsx b/apps/conciv/test/kit-controls.browser.test.tsx
index 078a8487ad..c4c400286d 100644
--- a/apps/conciv/test/kit-controls.browser.test.tsx
+++ b/apps/conciv/test/kit-controls.browser.test.tsx
@@ -1,6 +1,6 @@
import '@conciv/ui-kit-system/tokens.css'
import './helpers/utilities.css'
-import {afterEach, expect, test} from 'vitest'
+import {expect, test} from 'vitest'
import {page} from 'vitest/browser'
import {render} from '@solidjs/testing-library'
import type {JSX} from 'solid-js'
@@ -8,13 +8,9 @@ import type {ToolCallPart} from '@tanstack/ai-client'
import type {UiAnswerValue} from '@conciv/protocol/ui-types'
import {INERT_TOOL_CATALOG} from '@conciv/protocol/tool-view-types'
import {UiCard} from '@conciv/tools/cards'
-import {NoticeToaster, notify, toaster} from '../src/shell/notices.js'
+import {createNoticeStore} from '../src/shell/notices.js'
import {QuickTerminalHeader} from '../src/routes/quick.js'
-afterEach(() => {
- toaster.remove()
-})
-
function mount(view: () => JSX.Element): void {
render(view)
}
@@ -24,8 +20,9 @@ function uiPart(spec: unknown): ToolCallPart {
}
test('the way out of a notice explains itself with a tooltip a touch reader can reach, not a native title', async () => {
- mount(() => )
- notify('Command copied. Paste it in your terminal.')
+ const store = createNoticeStore()
+ mount(() => )
+ store.notify('Command copied. Paste it in your terminal.')
await page.getByRole('button', {name: 'Dismiss'}).hover()
diff --git a/apps/conciv/test/launch-actions.browser.test.tsx b/apps/conciv/test/launch-actions.browser.test.tsx
index d5b7539e97..40bc47ec92 100644
--- a/apps/conciv/test/launch-actions.browser.test.tsx
+++ b/apps/conciv/test/launch-actions.browser.test.tsx
@@ -3,14 +3,12 @@ import {page} from 'vitest/browser'
import type {GrabApi} from '@conciv/grab'
import {HostApiProvider} from '@conciv/extension'
import {ComposerActions} from '../src/composer/actions.js'
-import {NoticeToaster, toaster} from '../src/shell/notices.js'
import {installFakeCore, type FakeCore} from './helpers/fake-core.js'
import {mountPane, PANE_SESSION} from './helpers/pane-harness.js'
let core: FakeCore | null = null
afterEach(() => {
- toaster.remove()
core?.restore()
core = null
})
@@ -37,7 +35,6 @@ function mountActions(config: Parameters[0] = {}): FakeC
onNewSession={() => {}}
onStageGrab={() => {}}
/>
-
))
return fake
diff --git a/apps/conciv/test/notices.browser.test.tsx b/apps/conciv/test/notices.browser.test.tsx
index 0f3af3aef4..95f8bb5ac9 100644
--- a/apps/conciv/test/notices.browser.test.tsx
+++ b/apps/conciv/test/notices.browser.test.tsx
@@ -1,28 +1,25 @@
import '@conciv/ui-kit-system/tokens.css'
import './helpers/utilities.css'
-import {afterEach, expect, test} from 'vitest'
+import {expect, test} from 'vitest'
import {page} from 'vitest/browser'
import {render} from '@solidjs/testing-library'
import {createSignal, Show} from 'solid-js'
-import {NoticeToaster, notify, toaster} from '../src/shell/notices.js'
+import {createNoticeStore, type Notify} from '../src/shell/notices.js'
-afterEach(() => {
- toaster.remove()
-})
-
-function mountToaster(): {showToaster: (visible: boolean) => void} {
+function mountToaster(): {notify: Notify; showToaster: (visible: boolean) => void} {
+ const store = createNoticeStore()
const [standing, setStanding] = createSignal(true)
const mounted = render(() => (
another session
}>
-
+
))
mounted.container.className = 'chat-theme-conciv'
- return {showToaster: (visible) => setStanding(visible)}
+ return {notify: store.notify, showToaster: (visible) => setStanding(visible)}
}
test('a notice stands in the notifications region until it is dismissed by hand', async () => {
- mountToaster()
+ const {notify} = mountToaster()
notify('Command copied. Paste it in your terminal.')
@@ -36,7 +33,7 @@ test('a notice stands in the notifications region until it is dismissed by hand'
})
test('an alarming notice asks to be read at once, a plain one waits its turn', async () => {
- mountToaster()
+ const {notify} = mountToaster()
notify('Still connected to your terminal.', {tone: 'danger'})
@@ -48,7 +45,7 @@ test('an alarming notice asks to be read at once, a plain one waits its turn', a
})
test('the way out of a notice runs once and takes the notice with it', async () => {
- mountToaster()
+ const {notify} = mountToaster()
let handedBack = 0
notify('Now following fix the flaky test.', {
action: {
@@ -66,7 +63,7 @@ test('the way out of a notice runs once and takes the notice with it', async ()
})
test('a notice raised again under the same name replaces the one already standing', async () => {
- mountToaster()
+ const {notify} = mountToaster()
notify('Still connected to your terminal.', {key: 'hand-back', tone: 'danger'})
await expect.element(page.getByText('Still connected to your terminal.')).toBeVisible()
@@ -78,20 +75,20 @@ test('a notice raised again under the same name replaces the one already standin
})
test('a notice that offers a way out survives leaving the session it was raised in', async () => {
- const mounted = mountToaster()
+ const {notify, showToaster} = mountToaster()
notify('Now following fix the flaky test.', {action: {label: 'Undo', run: () => {}}})
await expect.element(page.getByText('Now following fix the flaky test.')).toBeVisible()
- mounted.showToaster(false)
+ showToaster(false)
await expect.element(page.getByText('another session')).toBeVisible()
- mounted.showToaster(true)
+ showToaster(true)
await expect.element(page.getByText('Now following fix the flaky test.')).toBeVisible()
await expect.element(page.getByRole('button', {name: 'Undo'})).toBeVisible()
})
test('an alarming notice that offers a way out shows both the way out and the way to dismiss', async () => {
- mountToaster()
+ const {notify} = mountToaster()
notify('Still connected to your terminal.', {tone: 'danger', action: {label: 'Hand it back', run: () => {}}})
@@ -101,7 +98,7 @@ test('an alarming notice that offers a way out shows both the way out and the wa
})
test('the way out of a notice explains itself with a tooltip a touch reader can reach', async () => {
- mountToaster()
+ const {notify} = mountToaster()
notify('Command copied. Paste it in your terminal.')
await page.getByRole('button', {name: 'Dismiss'}).hover()
diff --git a/apps/conciv/test/panel-connect.browser.test.tsx b/apps/conciv/test/panel-connect.browser.test.tsx
new file mode 100644
index 0000000000..767f13f437
--- /dev/null
+++ b/apps/conciv/test/panel-connect.browser.test.tsx
@@ -0,0 +1,71 @@
+import './helpers/utilities.css'
+import {afterEach, expect, test} from 'vitest'
+import {page} from 'vitest/browser'
+import {defineExtension, getHostApi} from '@conciv/extension'
+import {Show, type JSX} from 'solid-js'
+import {createShellHarness} from './helpers/shell-harness.js'
+import {expectRetryRecovers} from './helpers/retry-recovery.js'
+
+const PANEL_SESSION = 'conciv_1'
+const FOUND_API_BASE = 'http://found.test'
+const harness = createShellHarness(PANEL_SESSION)
+
+afterEach(harness.dispose)
+
+function ConnectProbe(): JSX.Element {
+ const connect = getHostApi().useConnect()
+ return (
+
+ )
+}
+
+const connectProbe = defineExtension({
+ name: 'connect-probe',
+ Component: () => (
+
+
+
+ ),
+}).client(() => ({value: {}}))
+
+const mountShell = (config: Parameters[1] = {}): void =>
+ harness.mountShell('/panel/connect?open=true', config, [connectProbe])
+
+const simulateFound = () => page.getByRole('button', {name: 'Simulate found'})
+const bindFailure = () => page.getByText(/conciv couldn.t connect to that workspace/)
+const serverError = () => page.getByText('Internal Server Error')
+const editor = () => page.getByRole('textbox', {name: 'Message the conciv agent'})
+
+test('a bind that fails with a transport failure shows the connect failure screen, and retrying against a healthy engine hands off to the panel', async () => {
+ mountShell({resolveTransportFails: true})
+
+ await simulateFound().click()
+
+ await expect.element(bindFailure(), {timeout: 8000}).toBeVisible()
+ await expect.element(page.getByRole('button', {name: 'Retry'})).toBeVisible()
+
+ await expectRetryRecovers(() => harness.core()?.setResolveTransportFails(false), editor, bindFailure)
+})
+
+test('a bind that fails with a server error shows the actual error, not the workspace-unreachable message', async () => {
+ mountShell({resolveRejects: true})
+
+ await expect.element(simulateFound(), {timeout: 8000}).toBeVisible()
+ await simulateFound().click()
+
+ await expect.element(serverError(), {timeout: 8000}).toBeVisible()
+ await expect.element(bindFailure()).not.toBeInTheDocument()
+
+ await expectRetryRecovers(() => harness.core()?.setResolveRejects(false), editor, serverError)
+})
+
+test('a bind that succeeds on the first try never shows the failure screen', async () => {
+ mountShell()
+
+ await simulateFound().click()
+
+ await expect.element(editor(), {timeout: 8000}).toBeVisible()
+ await expect.element(bindFailure()).not.toBeInTheDocument()
+})
diff --git a/apps/conciv/test/quick-add-pane.browser.test.tsx b/apps/conciv/test/quick-add-pane.browser.test.tsx
new file mode 100644
index 0000000000..edb3d6e1ae
--- /dev/null
+++ b/apps/conciv/test/quick-add-pane.browser.test.tsx
@@ -0,0 +1,48 @@
+import './helpers/utilities.css'
+import {afterEach, expect, test} from 'vitest'
+import {page} from 'vitest/browser'
+import {createShellHarness} from './helpers/shell-harness.js'
+import {sessionRow} from './helpers/fake-core.js'
+import {expectRetryRecovers} from './helpers/retry-recovery.js'
+
+const PANEL_SESSION = 'conciv_1'
+const harness = createShellHarness(PANEL_SESSION)
+const mountShell = (config: Parameters[1] = {}): void => harness.mountShell('/quick', config)
+
+afterEach(harness.dispose)
+
+const startFailure = () => page.getByText(/conciv could not start a pane/)
+const editor = () => page.getByRole('textbox', {name: 'Message the conciv agent'})
+
+test('a quick terminal pane that fails to start shows a retry action', async () => {
+ mountShell({resolveRejects: true})
+
+ await expect.element(startFailure(), {timeout: 8000}).toBeVisible()
+ await expect.element(page.getByRole('button', {name: 'Retry'})).toBeVisible()
+})
+
+test('retrying a failed quick terminal pane against a healthy engine starts it', async () => {
+ mountShell({resolveRejects: true})
+ await expect.element(startFailure(), {timeout: 8000}).toBeVisible()
+
+ await expectRetryRecovers(() => harness.core()?.setResolveRejects(false), editor, startFailure)
+})
+
+test('rapid double-trigger creates exactly one pane', async () => {
+ harness.mountShell('/quick?panes=conciv_1&focus=0', {
+ sessions: [sessionRow({id: 'conciv_1'})],
+ delays: {'/rpc/sessions/resolve': 300},
+ })
+ await expect.element(editor(), {timeout: 8000}).toBeVisible()
+
+ const splitButton = page.getByRole('button', {name: 'Split pane (Mod+D)'})
+ const firstClick = splitButton.click()
+ const secondClick = splitButton.click()
+ await Promise.all([firstClick, secondClick])
+
+ await harness.core()?.idle()
+ const addPaneCalls = harness
+ .core()
+ ?.calls.filter((call) => call.path === '/rpc/sessions/resolve' && Object.keys(call.body ?? {}).length === 0).length
+ expect(addPaneCalls).toBe(1)
+})
diff --git a/apps/conciv/test/reachability-flows.browser.test.tsx b/apps/conciv/test/reachability-flows.browser.test.tsx
new file mode 100644
index 0000000000..343a5d8028
--- /dev/null
+++ b/apps/conciv/test/reachability-flows.browser.test.tsx
@@ -0,0 +1,96 @@
+import './helpers/utilities.css'
+import {afterEach, expect, test} from 'vitest'
+import {page, userEvent} from 'vitest/browser'
+import {createShellHarness} from './helpers/shell-harness.js'
+import {expectRetryRecovers} from './helpers/retry-recovery.js'
+
+const PANEL_SESSION = 'conciv_1'
+const harness = createShellHarness(PANEL_SESSION)
+const mountShell = harness.mountShell
+
+afterEach(harness.dispose)
+
+const errorScreen = () => page.getByText(/couldn.t reach the engine/)
+const editor = () => page.getByRole('textbox', {name: 'Message the conciv agent'})
+const genericBoundary = () => page.getByText('Something went wrong!')
+const engineUnreachableNotice = () => page.getByText('conciv lost connection to the engine.')
+const serverError = () => page.getByText('Internal Server Error')
+
+test('a dead engine at boot shows our error screen, not the generic boundary, and Retry recovers it', async () => {
+ mountShell('/panel/latest?open=true', {networkFail: true})
+
+ await expect.element(errorScreen(), {timeout: 8000}).toBeVisible()
+ await expect.element(genericBoundary()).not.toBeInTheDocument()
+
+ harness.core()?.setNetworkFail(false)
+ await page
+ .getByRole('alert')
+ .filter({hasText: /couldn.t reach the engine/})
+ .getByRole('button', {name: 'Retry'})
+ .click()
+
+ await expect.element(editor(), {timeout: 8000}).toBeVisible()
+})
+
+test('a server error while resolving /panel/latest shows the actual error, not the unreachable message', async () => {
+ mountShell('/panel/latest?open=true', {resolveRejects: true})
+
+ await expect.element(serverError(), {timeout: 8000}).toBeVisible()
+ await expect.element(errorScreen()).not.toBeInTheDocument()
+ await expect.element(genericBoundary()).not.toBeInTheDocument()
+
+ await expectRetryRecovers(() => harness.core()?.setResolveRejects(false), editor, serverError)
+})
+
+test('a healthy engine resolves /panel/latest straight to the warm session', async () => {
+ mountShell('/panel/latest?open=true')
+
+ await expect.element(editor(), {timeout: 8000}).toBeVisible()
+ await expect.element(errorScreen()).not.toBeInTheDocument()
+})
+
+test('a sustained outage raises exactly one standing notice, and it clears once the engine returns', async () => {
+ mountShell(`/panel/${PANEL_SESSION}?open=true`)
+ await expect.element(editor(), {timeout: 8000}).toBeVisible()
+
+ harness.core()?.setNetworkFail(true)
+ await expect.element(engineUnreachableNotice(), {timeout: 8000}).toBeVisible()
+ await expect.element(page.getByRole('button', {name: 'Retry'})).toBeVisible()
+
+ harness.core()?.setNetworkFail(false)
+ await expect.element(engineUnreachableNotice(), {timeout: 8000}).not.toBeInTheDocument()
+})
+
+test('a 500 from an otherwise healthy engine never raises the unreachable notice', async () => {
+ mountShell(`/panel/${PANEL_SESSION}?open=true`, {rejectSend: true})
+ await expect.element(editor(), {timeout: 8000}).toBeVisible()
+
+ await editor().fill('rename the widget package')
+ await userEvent.keyboard('{Enter}')
+
+ await expect
+ .element(page.getByRole('region', {name: /Notifications/}))
+ .toHaveTextContent(/Internal Server Error|could not be sent/)
+ await expect.element(engineUnreachableNotice()).not.toBeInTheDocument()
+})
+
+test('a failing engine-info probe on an otherwise healthy connection never raises the unreachable notice', async () => {
+ mountShell(`/panel/${PANEL_SESSION}?open=true`, {rejectEngineProbe: true})
+
+ await expect.element(editor(), {timeout: 8000}).toBeVisible()
+ await harness.core()?.idle()
+ await expect.element(engineUnreachableNotice()).not.toBeInTheDocument()
+})
+
+test('the composer disables sending with a distinct message once the engine is unreachable', async () => {
+ mountShell(`/panel/${PANEL_SESSION}?open=true`)
+ await expect.element(editor(), {timeout: 8000}).toBeVisible()
+ await editor().fill('rename the widget package')
+
+ harness.core()?.setNetworkFail(true)
+
+ await expect
+ .element(page.getByRole('button', {name: 'conciv lost connection to the engine'}), {timeout: 8000})
+ .toBeVisible()
+ await expect.element(page.getByRole('button', {name: 'conciv lost connection to the engine'})).toBeDisabled()
+})
diff --git a/apps/conciv/test/send-checks.test.ts b/apps/conciv/test/send-checks.test.ts
index bba6f79e77..a2c4d10b6b 100644
--- a/apps/conciv/test/send-checks.test.ts
+++ b/apps/conciv/test/send-checks.test.ts
@@ -3,7 +3,7 @@ import {MAX_ATTACHMENT_RAW_BYTES} from '@conciv/protocol/chat-types'
import {WS_RPC_PAYLOAD_BUDGET_BYTES} from '@conciv/protocol/rpc-types'
import {checkSend, MAX_CONTENT_PARTS} from '../src/pane/send-checks.js'
-const ready = {busy: false, connected: true}
+const ready = {busy: false, connected: true, reachable: true}
function parts(count: number): {content: {type: 'text'; content: string}[]} {
return {content: Array.from({length: count}, () => ({type: 'text', content: 'x'}))}
@@ -20,7 +20,7 @@ test('turns an empty message down without saying anything', () => {
})
test('turns a send down while the conversation is being compressed', () => {
- expect(checkSend('rename the widget package', {busy: true, connected: true}).ok).toBe(false)
+ expect(checkSend('rename the widget package', {busy: true, connected: true, reachable: true}).ok).toBe(false)
})
test('says why it turned down too many attachments instead of dropping them', () => {
@@ -56,10 +56,19 @@ test('lets a message with a budget-sized attachment through', () => {
})
test('says the connection is down instead of swallowing the message', () => {
- const verdict = checkSend('rename the widget package', {busy: false, connected: false})
+ const verdict = checkSend('rename the widget package', {busy: false, connected: false, reachable: true})
expect(verdict).toEqual({
ok: false,
message: 'Not connected yet. Your message is still in the composer.',
tone: 'warn',
})
})
+
+test('says the engine is unreachable with a distinct message from the hydration case', () => {
+ const verdict = checkSend('rename the widget package', {busy: false, connected: false, reachable: false})
+ expect(verdict).toEqual({
+ ok: false,
+ message: 'conciv lost connection to the engine. Your message is still in the composer.',
+ tone: 'warn',
+ })
+})
diff --git a/packages/client/src/chat-connection.ts b/packages/client/src/chat-connection.ts
index b6e114273e..749a474328 100644
--- a/packages/client/src/chat-connection.ts
+++ b/packages/client/src/chat-connection.ts
@@ -1,14 +1,29 @@
import type {ModelMessage, StreamChunk, UIMessage} from '@tanstack/ai'
import type {SubscribeConnectionAdapter} from '@tanstack/ai-solid'
import {AsyncRetryer} from '@tanstack/pacer'
+import {ORPCError} from '@orpc/client'
import type {RpcClient} from '@conciv/contract'
import type {ChatContentPart} from '@conciv/protocol/chat-types'
export type ChatConnectionOptions = {
retryDelayMs?: number
+ offlineRetryDelayMs?: number
+ isOnline?: () => boolean
onRetry?: (error: unknown) => void
}
+const DEFAULT_RETRY_DELAY_MS = 500
+const DEFAULT_OFFLINE_RETRY_DELAY_MS = 2000
+
+export function chatRetryDelayMs(options: ChatConnectionOptions): number {
+ if (options.isOnline && !options.isOnline()) return options.offlineRetryDelayMs ?? DEFAULT_OFFLINE_RETRY_DELAY_MS
+ return options.retryDelayMs ?? DEFAULT_RETRY_DELAY_MS
+}
+
+export function isReachabilityError(error: unknown): boolean {
+ return !(error instanceof ORPCError)
+}
+
export type ChatConnection = SubscribeConnectionAdapter & {refresh: () => void}
function isRecord(value: unknown): value is Record {
@@ -80,10 +95,12 @@ async function openStream(
): Promise {
const retryer = new AsyncRetryer(async () => await rpc.chat.subscribe({sessionId}, {signal}), {
backoff: 'fixed',
- baseWait: options.retryDelayMs ?? 500,
+ baseWait: () => chatRetryDelayMs(options),
throwOnError: false,
maxAttempts: () => (signal.aborted ? 1 : Number.MAX_SAFE_INTEGER),
- onRetry: (_attempt, error) => options.onRetry?.(error),
+ onRetry: (_attempt, error) => {
+ if (isReachabilityError(error)) options.onRetry?.(error)
+ },
})
const abortRetryer = () => retryer.abort()
signal.addEventListener('abort', abortRetryer, {once: true})
@@ -122,7 +139,7 @@ async function* subscribeStream(
if (!attempt.signal.aborted) return
} catch (error) {
if (!stillListening(consumerSignal)) return
- if (!attempt.signal.aborted) options.onRetry?.(error)
+ if (!attempt.signal.aborted && isReachabilityError(error)) options.onRetry?.(error)
}
}
}
diff --git a/packages/client/src/index.ts b/packages/client/src/index.ts
index 789be95fc9..9aeaea7215 100644
--- a/packages/client/src/index.ts
+++ b/packages/client/src/index.ts
@@ -1,3 +1,4 @@
export * from './query-utils.js'
export * from './chat-connection.js'
export * from './use-chat-session.js'
+export * from './reachability.js'
diff --git a/packages/client/src/reachability.ts b/packages/client/src/reachability.ts
new file mode 100644
index 0000000000..22a03688de
--- /dev/null
+++ b/packages/client/src/reachability.ts
@@ -0,0 +1,104 @@
+import {createEffect, createSignal, onCleanup, type Accessor} from 'solid-js'
+import {Debouncer} from '@tanstack/pacer'
+import {onlineManager} from '@tanstack/query-core'
+import {isRetryableRpcFailure, subscribeRpcReachability} from '@conciv/contract'
+
+export const ENGINE_OFFLINE_GRACE_MS = 1000
+
+type OnlineSetup = (setOnline: (online: boolean) => void) => (() => void) | undefined
+
+function defaultBrowserSetup(setOnline: (online: boolean) => void): (() => void) | undefined {
+ if (typeof window === 'undefined' || typeof window.addEventListener !== 'function') return undefined
+ const goOnline = (): void => setOnline(true)
+ const goOffline = (): void => setOnline(false)
+ window.addEventListener('online', goOnline)
+ window.addEventListener('offline', goOffline)
+ return () => {
+ window.removeEventListener('online', goOnline)
+ window.removeEventListener('offline', goOffline)
+ }
+}
+
+type ReachabilityHub = {
+ setOnline: ((online: boolean) => void) | undefined
+ detachNative: (() => void) | undefined
+ registrationCount: number
+}
+
+const hub: ReachabilityHub = {setOnline: undefined, detachNative: undefined, registrationCount: 0}
+
+const hubSetup: OnlineSetup = (setOnline) => {
+ hub.setOnline = setOnline
+ hub.detachNative = defaultBrowserSetup(setOnline)
+ return () => {
+ hub.detachNative?.()
+ hub.detachNative = undefined
+ hub.setOnline = undefined
+ }
+}
+
+function registerReachabilitySource(): () => void {
+ if (hub.registrationCount === 0) onlineManager.setEventListener(hubSetup)
+ hub.registrationCount += 1
+ let released = false
+ return () => {
+ if (released) return
+ released = true
+ hub.registrationCount -= 1
+ if (hub.registrationCount === 0) onlineManager.setEventListener(defaultBrowserSetup)
+ }
+}
+
+export function setupEngineReachability(apiBase: string): () => void {
+ const releaseSource = registerReachabilitySource()
+ const unsubscribeRpc = subscribeRpcReachability(apiBase, (reachable) => hub.setOnline?.(reachable))
+ let disposed = false
+ return () => {
+ if (disposed) return
+ disposed = true
+ unsubscribeRpc()
+ releaseSource()
+ }
+}
+
+export function engineOnline(): Accessor {
+ const [online, setOnline] = createSignal(onlineManager.isOnline())
+ onCleanup(onlineManager.subscribe(setOnline))
+ return online
+}
+
+export function sustainedEngineOffline(graceMs = ENGINE_OFFLINE_GRACE_MS): Accessor {
+ const online = engineOnline()
+ const [sustained, setSustained] = createSignal(false)
+ const offlineDebouncer = new Debouncer(() => setSustained(true), {wait: graceMs})
+ createEffect(() => {
+ if (online()) {
+ offlineDebouncer.cancel()
+ setSustained(false)
+ return
+ }
+ offlineDebouncer.maybeExecute()
+ })
+ onCleanup(() => offlineDebouncer.cancel())
+ return sustained
+}
+
+const ENGINE_PROBE_INTERVAL_MS = 2000
+
+export function engineProbeRefetchInterval(reachable: boolean, intervalMs = ENGINE_PROBE_INTERVAL_MS): number | false {
+ return reachable ? false : intervalMs
+}
+
+export function subscribeEngineOnline(listener: () => void): () => void {
+ return onlineManager.subscribe((online) => {
+ if (online) listener()
+ })
+}
+
+export function voteEngineProbeSettled(succeeded: boolean, error?: unknown): void {
+ if (succeeded) {
+ onlineManager.setOnline(true)
+ return
+ }
+ onlineManager.setOnline(!isRetryableRpcFailure(true, error))
+}
diff --git a/packages/client/test/chat-reachability.test.ts b/packages/client/test/chat-reachability.test.ts
new file mode 100644
index 0000000000..fbefdc0a4a
--- /dev/null
+++ b/packages/client/test/chat-reachability.test.ts
@@ -0,0 +1,31 @@
+import {describe, expect, it} from 'vitest'
+import {ORPCError} from '@orpc/client'
+import {chatRetryDelayMs, isReachabilityError} from '../src/chat-connection.js'
+
+describe('chatRetryDelayMs', () => {
+ it('uses the normal retry delay when isOnline is not supplied', () => {
+ expect(chatRetryDelayMs({retryDelayMs: 25})).toBe(25)
+ })
+
+ it('uses the normal retry delay while the engine reports online', () => {
+ expect(chatRetryDelayMs({retryDelayMs: 25, isOnline: () => true})).toBe(25)
+ })
+
+ it('backs off to the offline retry delay while the engine reports offline', () => {
+ expect(chatRetryDelayMs({retryDelayMs: 25, offlineRetryDelayMs: 400, isOnline: () => false})).toBe(400)
+ })
+
+ it('falls back to the default offline delay when none is configured', () => {
+ expect(chatRetryDelayMs({isOnline: () => false})).toBe(2000)
+ })
+})
+
+describe('isReachabilityError', () => {
+ it('is false for an ORPCError: an expired-session retry is not a reachability signal, the server answered', () => {
+ expect(isReachabilityError(new ORPCError('NOT_FOUND'))).toBe(false)
+ })
+
+ it('is true for a transport-level failure', () => {
+ expect(isReachabilityError(new TypeError('fetch failed'))).toBe(true)
+ })
+})
diff --git a/packages/client/test/reachability.test.ts b/packages/client/test/reachability.test.ts
new file mode 100644
index 0000000000..d414a81da7
--- /dev/null
+++ b/packages/client/test/reachability.test.ts
@@ -0,0 +1,227 @@
+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'
+import {createRoot} from 'solid-js'
+import {ORPCError} from '@orpc/client'
+import {onlineManager} from '@tanstack/query-core'
+import {browserRpcConnection, closeBrowserRpcConnection} from '@conciv/contract'
+import {
+ fakeNativeSocketConstructor,
+ nextSocket,
+ resetFakeNativeSockets,
+} from '../../contract/test/helpers/fake-native-socket.js'
+import {
+ engineOnline,
+ engineProbeRefetchInterval,
+ setupEngineReachability,
+ sustainedEngineOffline,
+ voteEngineProbeSettled,
+} from '../src/reachability.js'
+
+beforeEach(() => {
+ resetFakeNativeSockets()
+ vi.stubGlobal('WebSocket', fakeNativeSocketConstructor)
+})
+
+afterEach(() => {
+ vi.unstubAllGlobals()
+ onlineManager.setEventListener(() => undefined)
+ onlineManager.setOnline(true)
+})
+
+function apiBase(name: string): string {
+ return `http://client-reachability-${name}.test`
+}
+
+describe('setupEngineReachability', () => {
+ it('drives onlineManager from rpc reachability votes and clears state on the returned cleanup', async () => {
+ const base = apiBase('setup')
+ let dispose = (): void => {}
+ let cleanup = (): void => {}
+ const online = createRoot((disposeRoot) => {
+ dispose = disposeRoot
+ cleanup = setupEngineReachability(base)
+ return engineOnline()
+ })
+ browserRpcConnection(base)
+ const socket = await nextSocket()
+ socket.open()
+ expect(online()).toBe(true)
+ cleanup()
+ closeBrowserRpcConnection(base)
+ dispose()
+ })
+
+ it('is re-entrant: calling it again for a new base does not leak the old subscription', () => {
+ const cleanupOne = setupEngineReachability(apiBase('one'))
+ const cleanupTwo = setupEngineReachability(apiBase('two'))
+ expect(cleanupOne).not.toBe(cleanupTwo)
+ cleanupOne()
+ cleanupTwo()
+ })
+
+ it('two roots coexist: disposing the first leaves the second still driving onlineManager', async () => {
+ const baseOne = apiBase('multiplex-first')
+ const baseTwo = apiBase('multiplex-second')
+ const cleanupOne = setupEngineReachability(baseOne)
+ const cleanupTwo = setupEngineReachability(baseTwo)
+ cleanupOne()
+ onlineManager.setOnline(false)
+ browserRpcConnection(baseTwo)
+ const socket = await nextSocket()
+ socket.open()
+ expect(onlineManager.isOnline()).toBe(true)
+ cleanupTwo()
+ closeBrowserRpcConnection(baseTwo)
+ })
+
+ it('rebind: disposing and re-setting-up a slot does not detach a concurrently active second root', async () => {
+ const otherBase = apiBase('rebind-other')
+ const firstSlotBase = apiBase('rebind-a')
+ const secondSlotBase = apiBase('rebind-b')
+ const cleanupOther = setupEngineReachability(otherBase)
+ let cleanupSlot = setupEngineReachability(firstSlotBase)
+ cleanupSlot()
+ cleanupSlot = setupEngineReachability(secondSlotBase)
+ onlineManager.setOnline(false)
+ browserRpcConnection(otherBase)
+ const socket = await nextSocket()
+ socket.open()
+ expect(onlineManager.isOnline()).toBe(true)
+ cleanupSlot()
+ cleanupOther()
+ closeBrowserRpcConnection(otherBase)
+ })
+
+ it('disposes cleanly regardless of order and remains reusable afterward', async () => {
+ const baseA = apiBase('order-a')
+ const baseB = apiBase('order-b')
+ const cleanupA = setupEngineReachability(baseA)
+ const cleanupB = setupEngineReachability(baseB)
+ cleanupB()
+ cleanupA()
+ expect(() => cleanupA()).not.toThrow()
+
+ const baseC = apiBase('order-c')
+ const cleanupC = setupEngineReachability(baseC)
+ onlineManager.setOnline(false)
+ browserRpcConnection(baseC)
+ const socket = await nextSocket()
+ socket.open()
+ expect(onlineManager.isOnline()).toBe(true)
+ cleanupC()
+ closeBrowserRpcConnection(baseC)
+ })
+})
+
+describe('engineOnline', () => {
+ it('seeds from the current onlineManager state and tracks subsequent changes', () => {
+ onlineManager.setOnline(false)
+ const observed = createRoot((dispose) => {
+ const online = engineOnline()
+ const seed = online()
+ onlineManager.setOnline(true)
+ const after = online()
+ dispose()
+ return {seed, after}
+ })
+ expect(observed).toEqual({seed: false, after: true})
+ })
+})
+
+describe('sustainedEngineOffline', () => {
+ it('does not raise until the offline state survives the grace window', () => {
+ vi.useFakeTimers()
+ let dispose = (): void => {}
+ try {
+ onlineManager.setOnline(true)
+ const sustained = createRoot((disposeRoot) => {
+ dispose = disposeRoot
+ return sustainedEngineOffline(1000)
+ })
+ expect(sustained()).toBe(false)
+ onlineManager.setOnline(false)
+ vi.advanceTimersByTime(500)
+ expect(sustained()).toBe(false)
+ vi.advanceTimersByTime(600)
+ expect(sustained()).toBe(true)
+ } finally {
+ dispose()
+ vi.useRealTimers()
+ }
+ })
+
+ it('a blip that recovers within the grace window never raises', () => {
+ vi.useFakeTimers()
+ let dispose = (): void => {}
+ try {
+ onlineManager.setOnline(true)
+ const sustained = createRoot((disposeRoot) => {
+ dispose = disposeRoot
+ return sustainedEngineOffline(1000)
+ })
+ onlineManager.setOnline(false)
+ vi.advanceTimersByTime(500)
+ onlineManager.setOnline(true)
+ vi.advanceTimersByTime(600)
+ expect(sustained()).toBe(false)
+ } finally {
+ dispose()
+ vi.useRealTimers()
+ }
+ })
+
+ it('applies the grace period even when the manager is already offline at initialization', () => {
+ vi.useFakeTimers()
+ let dispose = (): void => {}
+ try {
+ onlineManager.setOnline(false)
+ const sustained = createRoot((disposeRoot) => {
+ dispose = disposeRoot
+ return sustainedEngineOffline(1000)
+ })
+ expect(sustained()).toBe(false)
+ vi.advanceTimersByTime(999)
+ expect(sustained()).toBe(false)
+ vi.advanceTimersByTime(1)
+ expect(sustained()).toBe(true)
+ } finally {
+ dispose()
+ vi.useRealTimers()
+ }
+ })
+})
+
+describe('engineProbeRefetchInterval', () => {
+ it('stops polling once reachable', () => {
+ expect(engineProbeRefetchInterval(true)).toBe(false)
+ })
+
+ it('polls at the given interval while unreachable', () => {
+ expect(engineProbeRefetchInterval(false, 3000)).toBe(3000)
+ })
+})
+
+describe('voteEngineProbeSettled', () => {
+ it('marks the manager online when the probe settles successfully', () => {
+ onlineManager.setOnline(false)
+ voteEngineProbeSettled(true)
+ expect(onlineManager.isOnline()).toBe(true)
+ })
+
+ it('votes offline when the probe fails with a transport error', () => {
+ onlineManager.setOnline(true)
+ voteEngineProbeSettled(false, new TypeError('fetch failed'))
+ expect(onlineManager.isOnline()).toBe(false)
+ })
+
+ it('votes online when the probe fails with an ORPCError: the server answered, so it is reachable', () => {
+ onlineManager.setOnline(false)
+ voteEngineProbeSettled(false, new ORPCError('INTERNAL_SERVER_ERROR'))
+ expect(onlineManager.isOnline()).toBe(true)
+ })
+
+ it('defaults to a transport-failure vote when no error is supplied', () => {
+ onlineManager.setOnline(true)
+ voteEngineProbeSettled(false)
+ expect(onlineManager.isOnline()).toBe(false)
+ })
+})
diff --git a/packages/client/tsconfig.json b/packages/client/tsconfig.json
index b694503269..86f009cd8b 100644
--- a/packages/client/tsconfig.json
+++ b/packages/client/tsconfig.json
@@ -5,6 +5,7 @@
"tsBuildInfoFile": ".tsbuildinfo",
"rootDir": ".",
"noEmit": true,
+ "lib": ["ES2024", "DOM"],
"types": ["node"]
},
"include": ["src/**/*.ts"]
diff --git a/packages/client/vitest.config.ts b/packages/client/vitest.config.ts
index 8900ec366f..2d70cadb0a 100644
--- a/packages/client/vitest.config.ts
+++ b/packages/client/vitest.config.ts
@@ -4,7 +4,27 @@ import {ciTest} from '@conciv/vitest-config'
export default defineConfig({
test: {
...ciTest(),
- environment: 'node',
- include: ['test/**/*.test.ts', 'test/**/*.it.test.ts'],
+ projects: [
+ {
+ test: {
+ ...ciTest(),
+ name: 'client',
+ environment: 'node',
+ include: ['test/**/*.test.ts', 'test/**/*.it.test.ts'],
+ exclude: ['test/reachability.test.ts'],
+ },
+ },
+ {
+ resolve: {conditions: ['browser', 'development']},
+ ssr: {resolve: {conditions: ['browser', 'development']}},
+ test: {
+ ...ciTest(),
+ name: 'client-solid',
+ environment: 'node',
+ server: {deps: {inline: ['solid-js']}},
+ include: ['test/reachability.test.ts'],
+ },
+ },
+ ],
},
})
diff --git a/packages/contract/src/browser-transport.ts b/packages/contract/src/browser-transport.ts
index 9d609690cc..b27878dd38 100644
--- a/packages/contract/src/browser-transport.ts
+++ b/packages/contract/src/browser-transport.ts
@@ -31,11 +31,19 @@ export type BrowserRpcConnection = {
close: () => void
}
+export type ReachabilityListener = (reachable: boolean) => void
+
type Registry = Map
+type ReachabilityRegistry = Map>
+type ActiveConnectionRegistry = Map
declare global {
// eslint-disable-next-line no-var
var __concivBrowserRpcRegistryV1: Registry | undefined
+ // eslint-disable-next-line no-var
+ var __concivRpcReachabilityListenersV1: ReachabilityRegistry | undefined
+ // eslint-disable-next-line no-var
+ var __concivRpcReachabilityActiveV1: ActiveConnectionRegistry | undefined
}
function registry(): Registry {
@@ -43,6 +51,34 @@ function registry(): Registry {
return globalThis.__concivBrowserRpcRegistryV1
}
+function reachabilityListeners(): ReachabilityRegistry {
+ globalThis.__concivRpcReachabilityListenersV1 ??= new Map()
+ return globalThis.__concivRpcReachabilityListenersV1
+}
+
+function activeConnections(): ActiveConnectionRegistry {
+ globalThis.__concivRpcReachabilityActiveV1 ??= new Map()
+ return globalThis.__concivRpcReachabilityActiveV1
+}
+
+export function subscribeRpcReachability(apiBase: string, listener: ReachabilityListener): () => void {
+ const key = normalizeApiBase(apiBase)
+ const listeners = reachabilityListeners()
+ const forKey = listeners.get(key) ?? new Set()
+ forKey.add(listener)
+ listeners.set(key, forKey)
+ return () => {
+ forKey.delete(listener)
+ }
+}
+
+function voteReachability(key: string, connectionId: symbol, reachable: boolean): void {
+ if (activeConnections().get(key) !== connectionId) return
+ const forKey = reachabilityListeners().get(key)
+ if (!forKey) return
+ for (const listener of forKey) listener(reachable)
+}
+
function normalizeApiBase(apiBase: string): string {
const url = new URL(apiBase === '' ? '/' : apiBase, typeof location === 'undefined' ? undefined : location.href)
const path = url.pathname.endsWith('/') ? url.pathname.slice(0, -1) : url.pathname
@@ -55,18 +91,33 @@ function websocketUrl(apiBase: string): string {
return url.toString()
}
-function retryPlugin(alive: () => boolean): ClientRetryPlugin {
+function isAbortedFailure(error: unknown): boolean {
+ return error instanceof Error && error.name === 'AbortError'
+}
+
+export function isRetryableRpcFailure(alive: boolean, error: unknown): boolean {
+ return alive && !(error instanceof ORPCError) && !isAbortedFailure(error)
+}
+
+function retryPlugin(alive: () => boolean, vote: ReachabilityListener): ClientRetryPlugin {
return new ClientRetryPlugin({
default: {
retry: CONNECTION_LOSS_RETRIES,
retryDelay: CONNECTION_LOSS_RETRY_DELAY_MS,
- shouldRetry: (options) => alive() && !(options.error instanceof ORPCError),
+ shouldRetry: (options) => {
+ const retryable = isRetryableRpcFailure(alive(), options.error)
+ if (retryable) vote(false)
+ return retryable
+ },
+ onRetry: () => (isSuccess: boolean) => {
+ if (isSuccess) vote(true)
+ },
},
})
}
-function fetchLink(apiBase: string, alive: () => boolean): ClientLink {
- return new FetchRpcLink({url: `${apiBase}/rpc`, plugins: [retryPlugin(alive)]})
+function fetchLink(apiBase: string, alive: () => boolean, vote: ReachabilityListener): ClientLink {
+ return new FetchRpcLink({url: `${apiBase}/rpc`, plugins: [retryPlugin(alive, vote)]})
}
type SocketDelegate = LinkWebsocketClientOptions['websocket']
@@ -152,54 +203,92 @@ function reconnectingSocket(apiBase: string): ReconnectingWebSocket {
})
}
-function probedConnection(apiBase: string): BrowserRpcConnection {
+type SocketReachabilityWiring = {markDeliberate: () => void}
+
+function wireSocketReachability(
+ socket: ReconnectingWebSocket,
+ key: string,
+ connectionId: symbol,
+): SocketReachabilityWiring {
+ const state = {deliberate: false, openedSinceLastClose: false}
+ socket.addEventListener('open', () => {
+ state.openedSinceLastClose = true
+ voteReachability(key, connectionId, true)
+ })
+ socket.addEventListener('close', () => {
+ if (state.deliberate) return
+ if (state.openedSinceLastClose) {
+ state.openedSinceLastClose = false
+ return
+ }
+ voteReachability(key, connectionId, false)
+ })
+ return {
+ markDeliberate: () => {
+ state.deliberate = true
+ },
+ }
+}
+
+function probedConnection(key: string): BrowserRpcConnection {
+ const connectionId = Symbol('conciv-rpc-connection')
+ activeConnections().set(key, connectionId)
+ const vote = (reachable: boolean): void => voteReachability(key, connectionId, reachable)
const state: {open: boolean; transport: RpcTransport | null} = {open: true, transport: null}
const alive = (): boolean => state.open
- const socket = reconnectingSocket(apiBase)
+ const socket = reconnectingSocket(key)
+ const wiring = wireSocketReachability(socket, key, connectionId)
const settled = openedWithin(socket, PROBE_TIMEOUT_MS).then((opened): ClientLink => {
- if (!state.open) return fetchLink(apiBase, alive)
+ if (!state.open) return fetchLink(key, alive, vote)
if (opened) {
state.transport = 'websocket'
return new WebsocketRpcLink({
websocket: socketDelegate(socket, alive),
- plugins: [retryPlugin(alive)],
+ plugins: [retryPlugin(alive, vote)],
})
}
+ wiring.markDeliberate()
socket.close()
state.transport = 'fetch'
- console.warn(`[conciv] rpc websocket probe to ${apiBase} timed out; this tab falls back to fetch/SSE`)
- return fetchLink(apiBase, alive)
+ console.warn(`[conciv] rpc websocket probe to ${key} timed out; this tab falls back to fetch/SSE`)
+ return fetchLink(key, alive, vote)
})
return {
link: new DynamicLink(() => settled),
transport: () => state.transport,
close: () => {
+ wiring.markDeliberate()
disposeSocket(socket)
state.open = false
},
}
}
-function pinnedConnection(apiBase: string, transport: RpcTransport): BrowserRpcConnection {
+function pinnedConnection(key: string, transport: RpcTransport): BrowserRpcConnection {
+ const connectionId = Symbol('conciv-rpc-connection')
+ activeConnections().set(key, connectionId)
+ const vote = (reachable: boolean): void => voteReachability(key, connectionId, reachable)
const state = {open: true}
const alive = (): boolean => state.open
if (transport === 'fetch') {
return {
- link: fetchLink(apiBase, alive),
+ link: fetchLink(key, alive, vote),
transport: () => 'fetch',
close: () => {
state.open = false
},
}
}
- const socket = reconnectingSocket(apiBase)
+ const socket = reconnectingSocket(key)
+ const wiring = wireSocketReachability(socket, key, connectionId)
return {
link: new WebsocketRpcLink({
websocket: socketDelegate(socket, alive),
- plugins: [retryPlugin(alive)],
+ plugins: [retryPlugin(alive, vote)],
}),
transport: () => 'websocket',
close: () => {
+ wiring.markDeliberate()
disposeSocket(socket)
state.open = false
},
@@ -225,9 +314,40 @@ export function closeBrowserRpcConnection(apiBase: string): void {
const existing = connections.get(key)
if (!existing) return
connections.delete(key)
+ activeConnections().delete(key)
existing.close()
}
+export function reprobeBrowserRpcConnection(
+ apiBase: string,
+ preference: RpcTransportPreference = 'auto',
+): BrowserRpcConnection {
+ const key = normalizeApiBase(apiBase)
+ const connections = registry()
+ const existing = connections.get(key)
+ if (existing) {
+ connections.delete(key)
+ activeConnections().delete(key)
+ existing.close()
+ }
+ const created = preference === 'auto' ? probedConnection(key) : pinnedConnection(key, preference)
+ connections.set(key, created)
+ return created
+}
+
export function browserRpcTransport(apiBase: string): RpcTransport | null {
return registry().get(normalizeApiBase(apiBase))?.transport() ?? null
}
+
+export const RPC_UNBOUND_MESSAGE = 'conciv core not connected yet'
+
+export function dynamicBrowserRpcLink(
+ currentApiBase: () => string | null,
+ preference: RpcTransportPreference = 'auto',
+): ClientLink {
+ return new DynamicLink(() => {
+ const apiBase = currentApiBase()
+ if (apiBase === null) throw new Error(RPC_UNBOUND_MESSAGE)
+ return Promise.resolve(browserRpcConnection(apiBase, preference).link)
+ })
+}
diff --git a/packages/contract/src/client.ts b/packages/contract/src/client.ts
index f4fdd61b9e..b75942a54b 100644
--- a/packages/contract/src/client.ts
+++ b/packages/contract/src/client.ts
@@ -1,10 +1,11 @@
-import {createORPCClient, DynamicLink, type ClientLink} from '@orpc/client'
+import {createORPCClient} from '@orpc/client'
import {RPCLink} from '@orpc/client/fetch'
import type {ContractRouterClient} from '@orpc/contract'
import {contract} from './contract.js'
import {
- browserRpcConnection,
closeBrowserRpcConnection,
+ dynamicBrowserRpcLink,
+ RPC_UNBOUND_MESSAGE,
type RpcClientContext,
type RpcTransportPreference,
} from './browser-transport.js'
@@ -23,50 +24,41 @@ export function makeRpcClient(apiBase: string, options: RpcClientOptions = {}):
export type BrowserRpcClientOptions = {transport?: RpcTransportPreference}
-export function makeBrowserRpcClient(apiBase: string, options: BrowserRpcClientOptions = {}): RpcClient {
- return createORPCClient(browserRpcConnection(apiBase, options.transport).link)
-}
-
-export type DeferredRpcClient = {
+export type BrowserRpcClient = {
rpc: RpcClient
- bind: (apiBase: string) => void
bound: () => boolean
+ bind: (apiBase: string) => void
+ rebind: (apiBase: string) => void
close: () => void
}
-export function makeDeferredRpcClient(options: BrowserRpcClientOptions = {}): DeferredRpcClient {
- const state: {base: string | null; ready: Promise> | null} = {base: null, ready: null}
- const link = new DynamicLink(() => {
- if (!state.ready) throw new Error('conciv core not connected yet')
- return state.ready
- })
+export function makeBrowserRpcClient(
+ base: string | (() => string | null),
+ options: BrowserRpcClientOptions = {},
+): BrowserRpcClient {
+ const state: {accessor: () => string | null} = {accessor: typeof base === 'function' ? base : () => base}
+ const currentBase = (): string | null => state.accessor()
+ const link = dynamicBrowserRpcLink(currentBase, options.transport)
return {
rpc: createORPCClient(link),
+ bound: () => currentBase() !== null,
bind: (apiBase) => {
- if (state.base !== null) throw new Error('deferred rpc already bound')
- if (apiBase === '') throw new Error('deferred rpc cannot bind an empty api base')
- state.base = apiBase
- state.ready = Promise.resolve(browserRpcConnection(apiBase, options.transport).link)
+ if (currentBase() !== null) throw new Error('conciv rpc client already bound')
+ if (apiBase === '') throw new Error('conciv rpc cannot bind an empty api base')
+ state.accessor = () => apiBase
+ },
+ rebind: (nextApiBase) => {
+ const previous = currentBase()
+ if (previous !== null) closeBrowserRpcConnection(previous)
+ state.accessor = () => nextApiBase
},
- bound: () => state.base !== null,
close: () => {
- if (state.base === null) return
- closeBrowserRpcConnection(state.base)
+ const previous = currentBase()
+ if (previous === null) return
+ closeBrowserRpcConnection(previous)
+ state.accessor = () => null
},
}
}
-export type RebindableRpcClient = {rpc: RpcClient; rebind: (apiBase: string) => void; close: () => void}
-
-export function makeRebindableRpcClient(apiBase: string, options: BrowserRpcClientOptions = {}): RebindableRpcClient {
- const state = {base: apiBase}
- const link = new DynamicLink(() => browserRpcConnection(state.base, options.transport).link)
- return {
- rpc: createORPCClient(link),
- rebind: (nextApiBase) => {
- closeBrowserRpcConnection(state.base)
- state.base = nextApiBase
- },
- close: () => closeBrowserRpcConnection(state.base),
- }
-}
+export {RPC_UNBOUND_MESSAGE}
diff --git a/packages/contract/test/client.test.ts b/packages/contract/test/client.test.ts
index d600bb829d..d4734e6082 100644
--- a/packages/contract/test/client.test.ts
+++ b/packages/contract/test/client.test.ts
@@ -1,6 +1,6 @@
import {describe, expect, expectTypeOf, it} from 'vitest'
import type {SessionMeta} from '../src/rows.js'
-import {makeRpcClient, type RpcClient} from '../src/client.js'
+import {makeBrowserRpcClient, makeRpcClient, type RpcClient} from '../src/client.js'
describe('makeRpcClient', () => {
it('builds a typed client rooted at /rpc', async () => {
@@ -23,3 +23,89 @@ describe('makeRpcClient', () => {
expectTypeOf>>().toEqualTypeOf()
})
})
+
+describe('makeBrowserRpcClient', () => {
+ it('is bound immediately when constructed with a plain base string', () => {
+ const client = makeBrowserRpcClient('http://127.0.0.1:1')
+ expect(client.bound()).toBe(true)
+ client.close()
+ })
+
+ it('starts unbound when constructed with a null-returning accessor, and rejects calls with the current message until bound', async () => {
+ const client = makeBrowserRpcClient(() => null)
+ expect(client.bound()).toBe(false)
+ await expect(client.rpc.sessions.resolve({})).rejects.toThrow('conciv core not connected yet')
+ client.bind('http://127.0.0.1:1')
+ expect(client.bound()).toBe(true)
+ client.close()
+ })
+
+ it('throws on double bind', () => {
+ const client = makeBrowserRpcClient(() => null)
+ client.bind('http://127.0.0.1:1')
+ expect(() => client.bind('http://127.0.0.1:2')).toThrow()
+ client.close()
+ })
+
+ it('rejects an empty api base and keeps bound() false so a later bind is not silently swallowed', () => {
+ const client = makeBrowserRpcClient(() => null)
+ expect(() => client.bind('')).toThrow()
+ expect(client.bound()).toBe(false)
+ client.bind('http://127.0.0.1:1')
+ expect(client.bound()).toBe(true)
+ client.close()
+ })
+
+ it('rebind closes the previous connection and moves the client onto the new base', () => {
+ const client = makeBrowserRpcClient('http://127.0.0.1:1')
+ expect(client.bound()).toBe(true)
+ client.rebind('http://127.0.0.1:2')
+ expect(client.bound()).toBe(true)
+ client.close()
+ })
+
+ it('rejects calls after close instead of resurrecting the connection', async () => {
+ const client = makeBrowserRpcClient('http://127.0.0.1:1')
+ client.close()
+ expect(client.bound()).toBe(false)
+ await expect(client.rpc.sessions.resolve({})).rejects.toThrow('conciv core not connected yet')
+ })
+
+ it('close is idempotent: calling it twice does not throw', () => {
+ const client = makeBrowserRpcClient('http://127.0.0.1:1')
+ client.close()
+ expect(() => client.close()).not.toThrow()
+ })
+
+ it('re-reads a caller-supplied base accessor on every call instead of freezing it at construction', () => {
+ let currentBase: string | null = 'http://127.0.0.1:1'
+ const client = makeBrowserRpcClient(() => currentBase)
+ expect(client.bound()).toBe(true)
+ currentBase = 'http://127.0.0.1:2'
+ expect(client.bound()).toBe(true)
+ currentBase = null
+ expect(client.bound()).toBe(false)
+ client.close()
+ })
+
+ it('targets the base returned by the accessor at call time, not the base seen at construction', async () => {
+ const requests: string[] = []
+ const originalFetch = globalThis.fetch
+ globalThis.fetch = async (input, init) => {
+ requests.push(new Request(input, init).url)
+ return new Response(JSON.stringify({json: []}), {headers: {'content-type': 'application/json'}})
+ }
+ let currentBase = 'http://client-accessor-one.test'
+ const client = makeBrowserRpcClient(() => currentBase, {transport: 'fetch'})
+ try {
+ await client.rpc.sessions.list(undefined)
+ expect(requests[0]).toContain('client-accessor-one.test')
+ currentBase = 'http://client-accessor-two.test'
+ await client.rpc.sessions.list(undefined)
+ expect(requests[1]).toContain('client-accessor-two.test')
+ } finally {
+ globalThis.fetch = originalFetch
+ client.close()
+ }
+ })
+})
diff --git a/packages/contract/test/deferred-client.test.ts b/packages/contract/test/deferred-client.test.ts
deleted file mode 100644
index 4ada72802b..0000000000
--- a/packages/contract/test/deferred-client.test.ts
+++ /dev/null
@@ -1,29 +0,0 @@
-import {describe, expect, it} from 'vitest'
-import {makeDeferredRpcClient} from '../src/client.js'
-
-describe('makeDeferredRpcClient', () => {
- it('rejects calls before bind', async () => {
- const {rpc, bound} = makeDeferredRpcClient()
- expect(bound()).toBe(false)
- await expect(rpc.sessions.resolve({})).rejects.toThrow('conciv core not connected yet')
- })
- it('keeps the same rpc reference across bind', () => {
- const deferred = makeDeferredRpcClient()
- const before = deferred.rpc
- deferred.bind('http://127.0.0.1:1')
- expect(deferred.rpc).toBe(before)
- expect(deferred.bound()).toBe(true)
- })
- it('throws on double bind', () => {
- const deferred = makeDeferredRpcClient()
- deferred.bind('http://127.0.0.1:1')
- expect(() => deferred.bind('http://127.0.0.1:2')).toThrow()
- })
- it('rejects an empty api base and keeps bound() false so a later bind is not silently swallowed', () => {
- const deferred = makeDeferredRpcClient()
- expect(() => deferred.bind('')).toThrow()
- expect(deferred.bound()).toBe(false)
- deferred.bind('http://127.0.0.1:1')
- expect(deferred.bound()).toBe(true)
- })
-})
diff --git a/packages/contract/test/helpers/fake-native-socket.ts b/packages/contract/test/helpers/fake-native-socket.ts
new file mode 100644
index 0000000000..45ebdea143
--- /dev/null
+++ b/packages/contract/test/helpers/fake-native-socket.ts
@@ -0,0 +1,83 @@
+const NATIVE_CONNECTING = 0
+const NATIVE_OPEN = 1
+const NATIVE_CLOSING = 2
+const NATIVE_CLOSED = 3
+
+export type FakeNativeSocket = EventTarget & {
+ readonly CONNECTING: number
+ readonly OPEN: number
+ readonly CLOSING: number
+ readonly CLOSED: number
+ readyState: number
+ binaryType: string
+ bufferedAmount: number
+ send: () => void
+ close: () => void
+ open: () => void
+ fail: () => void
+}
+
+type Waiter = {afterCount: number; resolve: (socket: FakeNativeSocket) => void}
+
+let instances: FakeNativeSocket[] = []
+let waiters: Waiter[] = []
+
+function resolveReadyWaiters(): void {
+ const instance = instances[instances.length - 1]
+ if (!instance) return
+ const ready = waiters.filter((waiter) => instances.length > waiter.afterCount)
+ waiters = waiters.filter((waiter) => instances.length <= waiter.afterCount)
+ for (const waiter of ready) waiter.resolve(instance)
+}
+
+export function resetFakeNativeSockets(): void {
+ instances = []
+ waiters = []
+}
+
+function createFakeNativeSocket(): FakeNativeSocket {
+ const socket: FakeNativeSocket = Object.assign(new EventTarget(), {
+ CONNECTING: NATIVE_CONNECTING,
+ OPEN: NATIVE_OPEN,
+ CLOSING: NATIVE_CLOSING,
+ CLOSED: NATIVE_CLOSED,
+ readyState: NATIVE_CONNECTING,
+ binaryType: 'blob',
+ bufferedAmount: 0,
+ send: (): void => {},
+ close: (): void => {},
+ open: (): void => {},
+ fail: (): void => {},
+ })
+ socket.close = (): void => {
+ socket.readyState = NATIVE_CLOSING
+ queueMicrotask(() => {
+ socket.readyState = NATIVE_CLOSED
+ socket.dispatchEvent(new Event('close'))
+ })
+ }
+ socket.open = (): void => {
+ socket.readyState = NATIVE_OPEN
+ socket.dispatchEvent(new Event('open'))
+ }
+ socket.fail = (): void => {
+ socket.readyState = NATIVE_CLOSED
+ socket.dispatchEvent(new Event('close'))
+ }
+ return socket
+}
+
+export function fakeNativeSocketConstructor(): FakeNativeSocket {
+ const socket = createFakeNativeSocket()
+ instances.push(socket)
+ resolveReadyWaiters()
+ return socket
+}
+
+export function nextSocket(afterCount = 0): Promise {
+ const latest = instances[instances.length - 1]
+ if (instances.length > afterCount && latest) return Promise.resolve(latest)
+ return new Promise((resolve) => {
+ waiters.push({afterCount, resolve})
+ })
+}
diff --git a/packages/contract/test/reachability.test.ts b/packages/contract/test/reachability.test.ts
new file mode 100644
index 0000000000..f0377be169
--- /dev/null
+++ b/packages/contract/test/reachability.test.ts
@@ -0,0 +1,170 @@
+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'
+import {ORPCError} from '@orpc/client'
+import {
+ browserRpcConnection,
+ closeBrowserRpcConnection,
+ isRetryableRpcFailure,
+ reprobeBrowserRpcConnection,
+ subscribeRpcReachability,
+} from '../src/browser-transport.js'
+import {
+ fakeNativeSocketConstructor,
+ nextSocket,
+ resetFakeNativeSockets,
+ type FakeNativeSocket,
+} from './helpers/fake-native-socket.js'
+
+async function connectAndTrackVotes(base: string): Promise<{votes: boolean[]; socket: FakeNativeSocket}> {
+ const votes: boolean[] = []
+ subscribeRpcReachability(base, (reachable) => votes.push(reachable))
+ browserRpcConnection(base)
+ const socket = await nextSocket()
+ return {votes, socket}
+}
+
+beforeEach(() => {
+ resetFakeNativeSockets()
+ vi.stubGlobal('WebSocket', fakeNativeSocketConstructor)
+})
+
+afterEach(() => {
+ vi.unstubAllGlobals()
+})
+
+function apiBase(name: string): string {
+ return `http://reachability-${name}.test`
+}
+
+describe('subscribeRpcReachability edge discrimination', () => {
+ it('votes online when the probe socket opens', async () => {
+ const base = apiBase('open')
+ const {votes, socket} = await connectAndTrackVotes(base)
+ socket.open()
+ expect(votes).toEqual([true])
+ closeBrowserRpcConnection(base)
+ })
+
+ it('emits no edge for a deliberate close we initiate', async () => {
+ const base = apiBase('deliberate')
+ const {votes, socket} = await connectAndTrackVotes(base)
+ socket.open()
+ votes.length = 0
+ closeBrowserRpcConnection(base)
+ await new Promise((resolve) => setTimeout(resolve, 0))
+ expect(votes).toEqual([])
+ })
+
+ it('votes offline on a close following a failed connect attempt', async () => {
+ const base = apiBase('failed-connect')
+ const {votes, socket} = await connectAndTrackVotes(base)
+ socket.fail()
+ expect(votes).toEqual([false])
+ closeBrowserRpcConnection(base)
+ })
+
+ it('treats an established socket drop as a blip, not an immediate offline vote, then votes offline if the reconnect attempt also fails', async () => {
+ const base = apiBase('blip')
+ const {votes, socket} = await connectAndTrackVotes(base)
+ socket.open()
+ votes.length = 0
+ socket.fail()
+ expect(votes).toEqual([])
+ const reconnectAttempt = await nextSocket(1)
+ reconnectAttempt.fail()
+ expect(votes).toEqual([false])
+ closeBrowserRpcConnection(base)
+ })
+
+ it('drops stale votes from a connection reprobe has already replaced', async () => {
+ const base = apiBase('stale')
+ const {votes, socket: staleSocket} = await connectAndTrackVotes(base)
+ staleSocket.open()
+ votes.length = 0
+ reprobeBrowserRpcConnection(base)
+ const freshSocket = await nextSocket(1)
+ expect(freshSocket).not.toBe(staleSocket)
+ staleSocket.fail()
+ expect(votes).toEqual([])
+ freshSocket.open()
+ expect(votes).toEqual([true])
+ closeBrowserRpcConnection(base)
+ })
+})
+
+describe('isRetryableRpcFailure', () => {
+ it('never treats an ORPCError as retryable: the server answered, so it is reachable', () => {
+ expect(isRetryableRpcFailure(true, new ORPCError('BAD_REQUEST'))).toBe(false)
+ })
+
+ it('treats a transport failure as retryable while the connection is alive', () => {
+ expect(isRetryableRpcFailure(true, new TypeError('fetch failed'))).toBe(true)
+ })
+
+ it('never retries once the connection has been deliberately closed', () => {
+ expect(isRetryableRpcFailure(false, new TypeError('fetch failed'))).toBe(false)
+ })
+
+ it('never treats a self-initiated abort as retryable: the signal.reason a real AbortController produces', () => {
+ const controller = new AbortController()
+ controller.abort()
+ expect(isRetryableRpcFailure(true, controller.signal.reason)).toBe(false)
+ })
+
+ it('never treats the native AbortError DOMException fetch throws as retryable', () => {
+ expect(isRetryableRpcFailure(true, new DOMException('The operation was aborted.', 'AbortError'))).toBe(false)
+ })
+})
+
+describe('retry-settle reachability votes over the fetch transport', () => {
+ const originalFetch = globalThis.fetch
+
+ afterEach(() => {
+ globalThis.fetch = originalFetch
+ vi.useRealTimers()
+ })
+
+ it('votes offline on a transport failure and online once the retry settles', async () => {
+ vi.useFakeTimers()
+ const base = apiBase('fetch-retry')
+ let calls = 0
+ globalThis.fetch = vi.fn(async () => {
+ calls += 1
+ if (calls === 1) throw new TypeError('network error')
+ return new Response(JSON.stringify({json: []}), {headers: {'content-type': 'application/json'}})
+ })
+ const votes: boolean[] = []
+ subscribeRpcReachability(base, (reachable) => votes.push(reachable))
+ const connection = browserRpcConnection(base, 'fetch')
+ const {createORPCClient} = await import('@orpc/client')
+ const client = createORPCClient<{sessions: {list: (input: undefined) => Promise}}>(connection.link)
+ const pending = client.sessions.list(undefined)
+ await vi.advanceTimersByTimeAsync(300)
+ await pending
+ expect(votes).toEqual([false, true])
+ closeBrowserRpcConnection(base)
+ })
+
+ it('a retry settle from an already-closed connection never votes: closing revokes its vote eligibility', async () => {
+ vi.useFakeTimers()
+ const base = apiBase('fetch-retry-closed')
+ let calls = 0
+ globalThis.fetch = vi.fn(async () => {
+ calls += 1
+ if (calls === 1) throw new TypeError('network error')
+ return new Response(JSON.stringify({json: []}), {headers: {'content-type': 'application/json'}})
+ })
+ const votes: boolean[] = []
+ subscribeRpcReachability(base, (reachable) => votes.push(reachable))
+ const connection = browserRpcConnection(base, 'fetch')
+ const {createORPCClient} = await import('@orpc/client')
+ const client = createORPCClient<{sessions: {list: (input: undefined) => Promise}}>(connection.link)
+ const pending = client.sessions.list(undefined).catch(() => {})
+ await vi.advanceTimersByTimeAsync(0)
+ expect(votes).toEqual([false])
+ closeBrowserRpcConnection(base)
+ votes.length = 0
+ await vi.advanceTimersByTimeAsync(300)
+ await pending
+ expect(votes).toEqual([])
+ })
+})
diff --git a/packages/embed/src/mount-impl.tsx b/packages/embed/src/mount-impl.tsx
index a8976fbd36..e73769ea93 100644
--- a/packages/embed/src/mount-impl.tsx
+++ b/packages/embed/src/mount-impl.tsx
@@ -1,7 +1,8 @@
-import {createSignal} from 'solid-js'
+import {createRoot, createSignal} from 'solid-js'
import {render} from 'solid-js/web'
import {RouterProvider, createMemoryHistory} from '@tanstack/solid-router'
-import {makeDeferredRpcClient, makeRebindableRpcClient} from '@conciv/contract'
+import {makeBrowserRpcClient} from '@conciv/contract'
+import {engineOnline, subscribeEngineOnline} from '@conciv/client'
import {createWebStorageHistory} from '@conciv/storage-history'
import {
collectClientEffects,
@@ -86,7 +87,7 @@ function bootNormal(config: BootNormalConfig): BootResult {
rpc,
rebind: rebindClient,
close: closeConnection,
- } = makeRebindableRpcClient(config.apiBase, {
+ } = makeBrowserRpcClient(config.apiBase, {
transport: config.settings.transport,
})
@@ -113,17 +114,31 @@ function bootNormal(config: BootNormalConfig): BootResult {
const driver = makeDomPageDriver({tools: mountedClientTools(router), effects: mountedClientEffects(router)})
window.__CONCIV_PAGE_DRIVER__ = driver
+ const reachabilityRoot = createRoot((dispose) => ({isOnline: engineOnline(), dispose}))
+
const container = document.createElement('div')
config.root.appendChild(container)
const disposeApp = render(() => , container)
- let plane = startPagePlane({rpc, document, driver})
+ let plane = startPagePlane({
+ rpc,
+ document,
+ driver,
+ isOnline: reachabilityRoot.isOnline,
+ subscribeOnline: subscribeEngineOnline,
+ })
const rebind = (nextApiBase: string): void => {
rebindClient(nextApiBase)
storage.dispose()
plane.dispose()
setApiBase(nextApiBase)
- plane = startPagePlane({rpc, document, driver})
+ plane = startPagePlane({
+ rpc,
+ document,
+ driver,
+ isOnline: reachabilityRoot.isOnline,
+ subscribeOnline: subscribeEngineOnline,
+ })
router.options.context.queryClient.clear()
setConnectionGeneration((generation) => generation + 1)
}
@@ -137,6 +152,7 @@ function bootNormal(config: BootNormalConfig): BootResult {
() => disposeConcivRouter(router),
() => router.options.context.queryClient.clear(),
driver.dispose,
+ reachabilityRoot.dispose,
closeConnection,
]
return {dispose: () => runDisposers(disposers), rebind}
@@ -150,7 +166,8 @@ type BootConnectConfig = {
}
function bootConnect(config: BootConnectConfig): BootResult {
- const deferred = makeDeferredRpcClient({transport: config.settings.transport})
+ const deferred = makeBrowserRpcClient(() => null, {transport: config.settings.transport})
+ const reachabilityRoot = createRoot((dispose) => ({isOnline: engineOnline(), dispose}))
let boundApiBase: string | undefined
let planeDispose: (() => void) | undefined
@@ -159,7 +176,13 @@ function bootConnect(config: BootConnectConfig): BootResult {
boundApiBase = nextApiBase
deferred.bind(nextApiBase)
setApiBase(nextApiBase)
- planeDispose = startPagePlane({rpc: deferred.rpc, document, driver}).dispose
+ planeDispose = startPagePlane({
+ rpc: deferred.rpc,
+ document,
+ driver,
+ isOnline: reachabilityRoot.isOnline,
+ subscribeOnline: subscribeEngineOnline,
+ }).dispose
}
const hostRouter = window.__TSR_ROUTER__
const router = createConcivRouter({
@@ -188,6 +211,7 @@ function bootConnect(config: BootConnectConfig): BootResult {
() => disposeConcivRouter(router),
() => router.options.context.queryClient.clear(),
driver.dispose,
+ reachabilityRoot.dispose,
deferred.close,
]
return {dispose: () => runDisposers(disposers)}
diff --git a/packages/embed/tests/e2e/connection-pool.it.test.ts b/packages/embed/tests/e2e/connection-pool.it.test.ts
index 8b02e0614c..63062d6de2 100644
--- a/packages/embed/tests/e2e/connection-pool.it.test.ts
+++ b/packages/embed/tests/e2e/connection-pool.it.test.ts
@@ -1,32 +1,16 @@
import {expect, test, type BrowserContext, type Page} from '@playwright/test'
import {observeRpc, type RpcObserver} from '@conciv/extension-testkit/rpc-observer'
-import {bootEmbedKit, type EmbedKit} from '../helpers/boot.js'
-import {hostPage, serveHost} from '../helpers/host.js'
-import {proxyTo, type ProxyCore} from '../helpers/proxy.js'
import {setNavigation} from './helpers/navigation.js'
+import {setupProxiedEmbedSuite} from './helpers/proxied-suite.js'
const ASSISTANT_TEXT = 'Hello from conciv'
const SHARED_CONTEXT_TAB_COUNT = 6
const MOUNT_TIMEOUT_MS = 20_000
-let kit: EmbedKit
-let core: ProxyCore
-let host: {base: string; close: () => Promise}
-
-test.beforeAll(async () => {
- kit = await bootEmbedKit({text: ASSISTANT_TEXT})
- core = await proxyTo(kit.base)
- host = await serveHost(() => hostPage({apiBase: core.base, widget: '{"quickTerminal":false}'}))
-})
-
-test.afterAll(async () => {
- await host.close()
- await core.close()
- await kit.cleanup()
-})
+const suite = setupProxiedEmbedSuite({text: ASSISTANT_TEXT})
test.beforeEach(async () => {
- expect(await setNavigation(kit, [{href: '/'}])).toBe(true)
+ expect(await setNavigation(suite.kit(), [{href: '/'}])).toBe(true)
})
type Tab = {page: Page; observer: RpcObserver; httpRpcUrls: string[]}
@@ -39,7 +23,7 @@ async function openTab(context: BrowserContext): Promise {
if (pathname.startsWith('/rpc/') || pathname === '/rpc') httpRpcUrls.push(request.url())
})
const observer = observeRpc(page)
- await page.goto(host.base, {waitUntil: 'domcontentloaded'})
+ await page.goto(suite.host().base, {waitUntil: 'domcontentloaded'})
await expect(page.getByRole('button', {name: 'Open conciv chat'})).toBeVisible({timeout: MOUNT_TIMEOUT_MS})
return {page, observer, httpRpcUrls}
}
diff --git a/packages/embed/tests/e2e/dead-engine-boot.it.test.ts b/packages/embed/tests/e2e/dead-engine-boot.it.test.ts
new file mode 100644
index 0000000000..5c004ca46c
--- /dev/null
+++ b/packages/embed/tests/e2e/dead-engine-boot.it.test.ts
@@ -0,0 +1,49 @@
+import {expect, test} from '@playwright/test'
+import {bootEmbedKit, type EmbedKit} from '../helpers/boot.js'
+import {hostPage, reserveDeadPort, serveHost} from '../helpers/host.js'
+import {proxyTo, type ProxyCore} from '../helpers/proxy.js'
+
+const ASSISTANT_TEXT = 'Recovered from a dead boot'
+const MOUNT_TIMEOUT_MS = 30_000
+
+let kit: EmbedKit
+
+test.beforeAll(async () => {
+ kit = await bootEmbedKit({text: ASSISTANT_TEXT})
+})
+
+test.afterAll(async () => {
+ await kit.cleanup()
+})
+
+test.describe('the router error screen surfaces a dead engine at boot and Retry recovers it', () => {
+ test('FAB click against a connection-refused base shows our error screen, then Retry recovers once the engine is reachable', async ({
+ page,
+ }) => {
+ test.setTimeout(90_000)
+ const dead = await reserveDeadPort()
+ const host = await serveHost(() => hostPage({apiBase: dead.base, widget: '{"quickTerminal":false}'}))
+ let proxy: ProxyCore | null = null
+ try {
+ await page.goto(host.base, {waitUntil: 'domcontentloaded'})
+ await expect(page.getByRole('button', {name: 'Open conciv chat'})).toBeVisible({timeout: MOUNT_TIMEOUT_MS})
+ await page.getByRole('button', {name: 'Open conciv chat'}).click()
+
+ const errorScreen = page.getByRole('alert').filter({hasText: /couldn.t reach the engine/})
+ await expect(errorScreen).toBeVisible({timeout: MOUNT_TIMEOUT_MS})
+
+ proxy = await proxyTo(kit.base, {port: dead.port})
+
+ await errorScreen.getByRole('button', {name: 'Retry'}).click()
+
+ const composer = page.getByRole('textbox', {name: 'Message the conciv agent'})
+ await expect(composer).toBeVisible({timeout: MOUNT_TIMEOUT_MS})
+ await composer.fill('hi there')
+ await page.getByRole('button', {name: 'Send message'}).click()
+ await expect(page.getByText(ASSISTANT_TEXT).first()).toBeVisible({timeout: MOUNT_TIMEOUT_MS})
+ } finally {
+ await host.close()
+ if (proxy) await proxy.close()
+ }
+ })
+})
diff --git a/packages/embed/tests/e2e/forced-drop.it.test.ts b/packages/embed/tests/e2e/forced-drop.it.test.ts
index 34a99dc8bd..db9e1072c9 100644
--- a/packages/embed/tests/e2e/forced-drop.it.test.ts
+++ b/packages/embed/tests/e2e/forced-drop.it.test.ts
@@ -1,33 +1,17 @@
import {expect, test, type Page} from '@playwright/test'
-import {bootEmbedKit, type EmbedKit} from '../helpers/boot.js'
-import {hostPage, serveHost} from '../helpers/host.js'
-import {proxyTo, type ProxyCore} from '../helpers/proxy.js'
import {rpcObserverFor} from '@conciv/extension-testkit/rpc-observer'
import {setNavigation} from './helpers/navigation.js'
+import {setupProxiedEmbedSuite} from './helpers/proxied-suite.js'
const ASSISTANT_TEXT = 'Reply across the drop'
const FIRST_TEXT = 'first turn before the drop'
const SECOND_TEXT = 'second turn after the drop'
const MOUNT_TIMEOUT_MS = 20_000
-let kit: EmbedKit
-let core: ProxyCore
-let host: {base: string; close: () => Promise}
-
-test.beforeAll(async () => {
- kit = await bootEmbedKit({text: ASSISTANT_TEXT})
- core = await proxyTo(kit.base)
- host = await serveHost(() => hostPage({apiBase: core.base, widget: '{"quickTerminal":false}'}))
-})
-
-test.afterAll(async () => {
- await host.close()
- await core.close()
- await kit.cleanup()
-})
+const suite = setupProxiedEmbedSuite({text: ASSISTANT_TEXT})
test.beforeEach(async () => {
- expect(await setNavigation(kit, [{href: '/'}])).toBe(true)
+ expect(await setNavigation(suite.kit(), [{href: '/'}])).toBe(true)
})
async function sendTurn(page: Page, text: string): Promise {
@@ -44,7 +28,7 @@ test.describe('chat survives a forced websocket drop', () => {
page.on('pageerror', (error) => pageErrors.push(String(error)))
const observer = rpcObserverFor(page)
try {
- await page.goto(host.base, {waitUntil: 'domcontentloaded'})
+ await page.goto(suite.host().base, {waitUntil: 'domcontentloaded'})
await page.getByRole('button', {name: 'Open conciv chat'}).click()
await expect(page.getByRole('textbox', {name: 'Message the conciv agent'})).toBeVisible({
timeout: MOUNT_TIMEOUT_MS,
@@ -55,7 +39,7 @@ test.describe('chat survives a forced websocket drop', () => {
const socketsBefore = observer.socketCount()
const mark = observer.mark()
- core.dropConnections()
+ suite.core().dropConnections()
await sendTurn(page, SECOND_TEXT)
diff --git a/packages/embed/tests/e2e/helpers/proxied-suite.ts b/packages/embed/tests/e2e/helpers/proxied-suite.ts
new file mode 100644
index 0000000000..b17e56c1c8
--- /dev/null
+++ b/packages/embed/tests/e2e/helpers/proxied-suite.ts
@@ -0,0 +1,40 @@
+import {test} from '@playwright/test'
+import {bootEmbedKit, type EmbedKit} from '../../helpers/boot.js'
+import {hostPage, serveHost} from '../../helpers/host.js'
+import {proxyTo, type ProxyCore} from '../../helpers/proxy.js'
+
+export type ProxiedEmbedSuite = {
+ kit: () => EmbedKit
+ core: () => ProxyCore
+ host: () => {base: string; close: () => Promise}
+}
+
+export function setupProxiedEmbedSuite(
+ opts: {
+ text?: string
+ widget?: string
+ proxy?: {blockUpgrades?: boolean; port?: number}
+ } = {},
+): ProxiedEmbedSuite {
+ let kit: EmbedKit
+ let core: ProxyCore
+ let host: {base: string; close: () => Promise}
+
+ test.beforeAll(async () => {
+ kit = await bootEmbedKit({text: opts.text})
+ core = await proxyTo(kit.base, opts.proxy)
+ host = await serveHost(() => hostPage({apiBase: core.base, widget: opts.widget ?? '{"quickTerminal":false}'}))
+ })
+
+ test.afterAll(async () => {
+ await host.close()
+ await core.close()
+ await kit.cleanup()
+ })
+
+ return {
+ kit: () => kit,
+ core: () => core,
+ host: () => host,
+ }
+}
diff --git a/packages/embed/tests/e2e/mid-session-outage.it.test.ts b/packages/embed/tests/e2e/mid-session-outage.it.test.ts
new file mode 100644
index 0000000000..39f72c07f1
--- /dev/null
+++ b/packages/embed/tests/e2e/mid-session-outage.it.test.ts
@@ -0,0 +1,48 @@
+import {expect, test} from '@playwright/test'
+import {holdRpcCalls} from '@conciv/extension-testkit/rpc-fault'
+import {bootEmbedKit, type EmbedKit} from '../helpers/boot.js'
+import {hostPage, serveHost} from '../helpers/host.js'
+import {chatBox, openChatPanel} from './helpers/chat.js'
+
+const ASSISTANT_TEXT = 'Recovered mid-session'
+const MOUNT_TIMEOUT_MS = 30_000
+
+let kit: EmbedKit
+let host: {base: string; close: () => Promise}
+
+test.beforeAll(async () => {
+ kit = await bootEmbedKit({text: ASSISTANT_TEXT})
+ host = await serveHost(() => hostPage({apiBase: kit.base, widget: '{"quickTerminal":false}'}))
+})
+
+test.afterAll(async () => {
+ await host.close()
+ await kit.cleanup()
+})
+
+test.describe('a mid-session outage raises the standing notice and disables sending, release auto-clears both', () => {
+ test('holding all rpc traffic surfaces the notice and a disabled send control, releasing it clears both', async ({
+ page,
+ }) => {
+ test.setTimeout(90_000)
+ const hold = await holdRpcCalls(page)
+ await page.goto(host.base, {waitUntil: 'domcontentloaded'})
+ await openChatPanel(page)
+
+ const composer = chatBox(page)
+ await composer.fill('a message queued during the outage')
+
+ hold.hold()
+
+ const notice = page.getByText('conciv lost connection to the engine.')
+ await expect(notice).toBeVisible({timeout: MOUNT_TIMEOUT_MS})
+ const disabledSend = page.getByRole('button', {name: 'conciv lost connection to the engine'})
+ await expect(disabledSend).toBeVisible({timeout: MOUNT_TIMEOUT_MS})
+ await expect(disabledSend).toBeDisabled()
+
+ hold.release()
+
+ await expect(notice).not.toBeVisible({timeout: MOUNT_TIMEOUT_MS})
+ await expect(page.getByRole('button', {name: 'Send message'})).toBeVisible({timeout: MOUNT_TIMEOUT_MS})
+ })
+})
diff --git a/packages/embed/tests/e2e/transport-reprobe-retry.it.test.ts b/packages/embed/tests/e2e/transport-reprobe-retry.it.test.ts
new file mode 100644
index 0000000000..11d450601f
--- /dev/null
+++ b/packages/embed/tests/e2e/transport-reprobe-retry.it.test.ts
@@ -0,0 +1,44 @@
+import {expect, test} from '@playwright/test'
+import {observeRpc} from '@conciv/extension-testkit/rpc-observer'
+import {holdRpcCalls} from '@conciv/extension-testkit/rpc-fault'
+import {chatBox, openChatPanel} from './helpers/chat.js'
+import {setupProxiedEmbedSuite} from './helpers/proxied-suite.js'
+
+const ASSISTANT_TEXT = 'Reprobed reply'
+const MOUNT_TIMEOUT_MS = 30_000
+
+const suite = setupProxiedEmbedSuite({text: ASSISTANT_TEXT, proxy: {blockUpgrades: true}})
+
+test.describe('a manual Retry after upgrades unblock re-probes the transport from scratch', () => {
+ test('rides the websocket on the next completed call once Retry re-probes past the sticky fetch transport', async ({
+ page,
+ }) => {
+ test.setTimeout(120_000)
+ const observer = observeRpc(page)
+ await page.goto(suite.host().base, {waitUntil: 'domcontentloaded'})
+ await openChatPanel(page)
+
+ const composer = chatBox(page)
+ await composer.fill('while upgrades are blocked')
+ await page.getByRole('button', {name: 'Send message'}).click()
+ const blocked = await observer.completed({path: ['chat', 'send'], timeout: MOUNT_TIMEOUT_MS})
+ expect(blocked.transport).toBe('fetch')
+
+ const hold = await holdRpcCalls(page)
+ hold.hold()
+
+ const retryButton = page.getByRole('button', {name: 'Retry'})
+ await expect(retryButton).toBeVisible({timeout: MOUNT_TIMEOUT_MS})
+
+ const mark = observer.mark()
+ await retryButton.click()
+ suite.core().setUpgradesBlocked(false)
+ hold.release()
+ await expect(composer).toBeVisible({timeout: MOUNT_TIMEOUT_MS})
+
+ await composer.fill('after the upgrade path opens')
+ await page.getByRole('button', {name: 'Send message'}).click()
+ const reprobed = await observer.completed({path: ['chat', 'send'], since: mark, timeout: MOUNT_TIMEOUT_MS})
+ expect(reprobed.transport).toBe('websocket')
+ })
+})
diff --git a/packages/embed/tests/helpers/host.ts b/packages/embed/tests/helpers/host.ts
index 2334353ff7..c574c92176 100644
--- a/packages/embed/tests/helpers/host.ts
+++ b/packages/embed/tests/helpers/host.ts
@@ -45,13 +45,23 @@ export function handleHostPage(body?: string): string {