From cda92789769427d3b236fb08c178ee6827f9e332 Mon Sep 17 00:00:00 2001
From: Omri Katz <9701896+omridevk@users.noreply.github.com>
Date: Fri, 14 Aug 2026 05:52:09 +0300
Subject: [PATCH 01/12] feat(contract): reachability seam + single rebindable
rpc client factory (#350 wave 1)
Adds subscribeRpcReachability to browser-transport.ts (deliberate-close guard,
stale-connection vote guard, ORPCError-never-offline discriminator) feeding
onlineManager wiring in @conciv/client (setupEngineReachability, engineOnline,
sustainedEngineOffline debounce, engine probe refetch-interval helper).
Collapses makeBrowserRpcClient/makeDeferredRpcClient/makeRebindableRpcClient
into one makeBrowserRpcClient(base, options) backed by a per-call
dynamicBrowserRpcLink, adds reprobeBrowserRpcConnection, and updates every
call site (entry-standalone, mount-impl, ext-rpc, client-host). Gates the
chat resubscribe loop and page-plane pump on the ORPCError discriminator and
reachability, and fixes the whiteboard change-feed to resubscribe instead of
dying on a reprobe-triggered AbortError.
Co-Authored-By: Claude Fable 5
---
apps/conciv/src/entry-standalone.tsx | 2 +-
packages/client/package.json | 1 +
packages/client/src/chat-connection.ts | 23 ++-
packages/client/src/index.ts | 1 +
packages/client/src/reachability.ts | 64 ++++++
.../client/test/chat-reachability.test.ts | 31 +++
packages/client/test/reachability.test.ts | 153 +++++++++++++++
packages/client/tsconfig.json | 1 +
packages/client/vitest.config.ts | 24 ++-
packages/contract/src/browser-transport.ts | 142 ++++++++++++--
packages/contract/src/client.ts | 55 ++----
packages/contract/test/client.test.ts | 43 ++++-
.../contract/test/deferred-client.test.ts | 29 ---
packages/contract/test/reachability.test.ts | 182 ++++++++++++++++++
packages/embed/src/mount-impl.tsx | 6 +-
packages/extension/src/client-host.ts | 2 +-
packages/extension/src/ext-rpc.ts | 7 +-
.../whiteboard/src/client/change-feed.ts | 67 +++++--
packages/page/src/index.ts | 24 ++-
packages/page/test/page-plane-poll.test.ts | 12 ++
pnpm-lock.yaml | 36 ++--
21 files changed, 775 insertions(+), 130 deletions(-)
create mode 100644 packages/client/src/reachability.ts
create mode 100644 packages/client/test/chat-reachability.test.ts
create mode 100644 packages/client/test/reachability.test.ts
delete mode 100644 packages/contract/test/deferred-client.test.ts
create mode 100644 packages/contract/test/reachability.test.ts
create mode 100644 packages/page/test/page-plane-poll.test.ts
diff --git a/apps/conciv/src/entry-standalone.tsx b/apps/conciv/src/entry-standalone.tsx
index c65d5db6cd..c715307631 100644
--- a/apps/conciv/src/entry-standalone.tsx
+++ b/apps/conciv/src/entry-standalone.tsx
@@ -10,7 +10,7 @@ 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,
diff --git a/packages/client/package.json b/packages/client/package.json
index 5c66097807..43c1cd4de4 100644
--- a/packages/client/package.json
+++ b/packages/client/package.json
@@ -43,6 +43,7 @@
"@conciv/protocol": "workspace:^",
"@orpc/client": "catalog:",
"@orpc/tanstack-query": "catalog:",
+ "@solid-primitives/scheduled": "^1.5.3",
"@tanstack/ai": "catalog:",
"@tanstack/ai-solid": "catalog:",
"@tanstack/pacer": "^0.21.1",
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..0f3ec57fdf
--- /dev/null
+++ b/packages/client/src/reachability.ts
@@ -0,0 +1,64 @@
+import {createEffect, createSignal, onCleanup, type Accessor} from 'solid-js'
+import {debounce} from '@solid-primitives/scheduled'
+import {onlineManager} from '@tanstack/query-core'
+import {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)
+ }
+}
+
+function rpcReachabilitySetup(apiBase: string): OnlineSetup {
+ return (setOnline) => {
+ const unsubscribeRpc = subscribeRpcReachability(apiBase, (reachable) => setOnline(reachable))
+ const detachNative = defaultBrowserSetup(setOnline)
+ return () => {
+ unsubscribeRpc()
+ detachNative?.()
+ }
+ }
+}
+
+export function setupEngineReachability(apiBase: string): () => void {
+ onlineManager.setEventListener(rpcReachabilitySetup(apiBase))
+ return () => onlineManager.setEventListener(defaultBrowserSetup)
+}
+
+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(!online())
+ const scheduleOffline = debounce(() => setSustained(true), graceMs)
+ createEffect(() => {
+ if (online()) {
+ scheduleOffline.clear()
+ setSustained(false)
+ return
+ }
+ scheduleOffline()
+ })
+ onCleanup(() => scheduleOffline.clear())
+ return sustained
+}
+
+const ENGINE_PROBE_INTERVAL_MS = 2000
+
+export function engineProbeRefetchInterval(reachable: boolean, intervalMs = ENGINE_PROBE_INTERVAL_MS): number | false {
+ return reachable ? false : intervalMs
+}
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..725507dd96
--- /dev/null
+++ b/packages/client/test/reachability.test.ts
@@ -0,0 +1,153 @@
+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'
+import {createRoot} from 'solid-js'
+import {onlineManager} from '@tanstack/query-core'
+import {browserRpcConnection, closeBrowserRpcConnection} from '@conciv/contract'
+import {
+ engineOnline,
+ engineProbeRefetchInterval,
+ setupEngineReachability,
+ sustainedEngineOffline,
+} from '../src/reachability.js'
+
+const NATIVE_CONNECTING = 0
+const NATIVE_OPEN = 1
+const NATIVE_CLOSING = 2
+const NATIVE_CLOSED = 3
+
+class FakeNativeSocket extends EventTarget {
+ static instances: FakeNativeSocket[] = []
+ readonly CONNECTING = NATIVE_CONNECTING
+ readonly OPEN = NATIVE_OPEN
+ readonly CLOSING = NATIVE_CLOSING
+ readonly CLOSED = NATIVE_CLOSED
+ readyState = NATIVE_CONNECTING
+ binaryType = 'blob'
+ bufferedAmount = 0
+
+ constructor() {
+ super()
+ FakeNativeSocket.instances.push(this)
+ }
+
+ send(): void {}
+
+ close(): void {
+ this.readyState = NATIVE_CLOSING
+ }
+
+ open(): void {
+ this.readyState = NATIVE_OPEN
+ this.dispatchEvent(new Event('open'))
+ }
+}
+
+async function nextSocket(afterCount = 0): Promise {
+ while (FakeNativeSocket.instances.length <= afterCount) await new Promise((resolve) => setTimeout(resolve, 5))
+ const instance = FakeNativeSocket.instances[FakeNativeSocket.instances.length - 1]
+ if (!instance) throw new Error('expected a fake socket instance')
+ return instance
+}
+
+let originalWebSocket: typeof globalThis.WebSocket | undefined
+
+beforeEach(() => {
+ FakeNativeSocket.instances = []
+ originalWebSocket = globalThis.WebSocket
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ globalThis.WebSocket = FakeNativeSocket as any
+})
+
+afterEach(() => {
+ globalThis.WebSocket = originalWebSocket as typeof globalThis.WebSocket
+ 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)
+ cleanupTwo()
+ })
+})
+
+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()
+ try {
+ onlineManager.setOnline(true)
+ const sustained = createRoot(() => sustainedEngineOffline(1000))
+ expect(sustained()).toBe(false)
+ onlineManager.setOnline(false)
+ vi.advanceTimersByTime(500)
+ expect(sustained()).toBe(false)
+ vi.advanceTimersByTime(600)
+ expect(sustained()).toBe(true)
+ } finally {
+ vi.useRealTimers()
+ }
+ })
+
+ it('a blip that recovers within the grace window never raises', () => {
+ vi.useFakeTimers()
+ try {
+ onlineManager.setOnline(true)
+ const sustained = createRoot(() => sustainedEngineOffline(1000))
+ onlineManager.setOnline(false)
+ vi.advanceTimersByTime(500)
+ onlineManager.setOnline(true)
+ vi.advanceTimersByTime(600)
+ expect(sustained()).toBe(false)
+ } finally {
+ 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)
+ })
+})
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..a117f8d5a1 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,29 @@ function websocketUrl(apiBase: string): string {
return url.toString()
}
-function retryPlugin(alive: () => boolean): ClientRetryPlugin {
+export function isRetryableRpcFailure(alive: boolean, error: unknown): boolean {
+ return alive && !(error instanceof ORPCError)
+}
+
+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 +199,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
},
@@ -228,6 +313,35 @@ export function closeBrowserRpcConnection(apiBase: string): void {
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)
+ 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..9ef9ba0bca 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,36 @@ 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: {base: string | null} = {base: typeof base === 'function' ? base() : base}
+ const link = dynamicBrowserRpcLink(() => state.base, options.transport)
return {
rpc: createORPCClient(link),
+ bound: () => state.base !== 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')
+ if (state.base !== null) throw new Error('conciv rpc client already bound')
+ if (apiBase === '') throw new Error('conciv rpc cannot bind an empty api base')
state.base = apiBase
- state.ready = Promise.resolve(browserRpcConnection(apiBase, options.transport).link)
- },
- bound: () => state.base !== null,
- close: () => {
- if (state.base === null) return
- closeBrowserRpcConnection(state.base)
},
- }
-}
-
-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)
+ if (state.base !== null) closeBrowserRpcConnection(state.base)
state.base = nextApiBase
},
- close: () => closeBrowserRpcConnection(state.base),
+ close: () => {
+ if (state.base !== null) 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..4fd3cba84e 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,44 @@ 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()
+ })
+})
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/reachability.test.ts b/packages/contract/test/reachability.test.ts
new file mode 100644
index 0000000000..9b548b7632
--- /dev/null
+++ b/packages/contract/test/reachability.test.ts
@@ -0,0 +1,182 @@
+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'
+
+const NATIVE_CONNECTING = 0
+const NATIVE_OPEN = 1
+const NATIVE_CLOSING = 2
+const NATIVE_CLOSED = 3
+
+class FakeNativeSocket extends EventTarget {
+ static instances: FakeNativeSocket[] = []
+ readonly CONNECTING = NATIVE_CONNECTING
+ readonly OPEN = NATIVE_OPEN
+ readonly CLOSING = NATIVE_CLOSING
+ readonly CLOSED = NATIVE_CLOSED
+ readyState = NATIVE_CONNECTING
+ binaryType = 'blob'
+ bufferedAmount = 0
+
+ constructor() {
+ super()
+ FakeNativeSocket.instances.push(this)
+ }
+
+ send(): void {}
+
+ close(): void {
+ this.readyState = NATIVE_CLOSING
+ queueMicrotask(() => {
+ this.readyState = NATIVE_CLOSED
+ this.dispatchEvent(new Event('close'))
+ })
+ }
+
+ open(): void {
+ this.readyState = NATIVE_OPEN
+ this.dispatchEvent(new Event('open'))
+ }
+
+ fail(): void {
+ this.readyState = NATIVE_CLOSED
+ this.dispatchEvent(new Event('close'))
+ }
+}
+
+async function nextSocket(afterCount = 0): Promise {
+ while (FakeNativeSocket.instances.length <= afterCount) await new Promise((resolve) => setTimeout(resolve, 5))
+ const instance = FakeNativeSocket.instances[FakeNativeSocket.instances.length - 1]
+ if (!instance) throw new Error('expected a fake socket instance')
+ return instance
+}
+
+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}
+}
+
+let originalWebSocket: typeof globalThis.WebSocket | undefined
+
+beforeEach(() => {
+ FakeNativeSocket.instances = []
+ originalWebSocket = globalThis.WebSocket
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ globalThis.WebSocket = FakeNativeSocket as any
+})
+
+afterEach(() => {
+ globalThis.WebSocket = originalWebSocket as typeof globalThis.WebSocket
+})
+
+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)
+ })
+})
+
+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)
+ })
+})
diff --git a/packages/embed/src/mount-impl.tsx b/packages/embed/src/mount-impl.tsx
index a8976fbd36..995d565120 100644
--- a/packages/embed/src/mount-impl.tsx
+++ b/packages/embed/src/mount-impl.tsx
@@ -1,7 +1,7 @@
import {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 {createWebStorageHistory} from '@conciv/storage-history'
import {
collectClientEffects,
@@ -86,7 +86,7 @@ function bootNormal(config: BootNormalConfig): BootResult {
rpc,
rebind: rebindClient,
close: closeConnection,
- } = makeRebindableRpcClient(config.apiBase, {
+ } = makeBrowserRpcClient(config.apiBase, {
transport: config.settings.transport,
})
@@ -150,7 +150,7 @@ type BootConnectConfig = {
}
function bootConnect(config: BootConnectConfig): BootResult {
- const deferred = makeDeferredRpcClient({transport: config.settings.transport})
+ const deferred = makeBrowserRpcClient(() => null, {transport: config.settings.transport})
let boundApiBase: string | undefined
let planeDispose: (() => void) | undefined
diff --git a/packages/extension/src/client-host.ts b/packages/extension/src/client-host.ts
index 80b043533a..6f4819060d 100644
--- a/packages/extension/src/client-host.ts
+++ b/packages/extension/src/client-host.ts
@@ -38,7 +38,7 @@ export function ensureEffectsSurface(options?: {styles?: string}): HTMLElement {
}
export async function openSource(apiBase: string, locateResult: LocateResult): Promise {
- const rpc = makeBrowserRpcClient(apiBase)
+ const {rpc} = makeBrowserRpcClient(apiBase)
try {
if (locateResult.source) {
await rpc.editor.open({file: locateResult.source.file, line: locateResult.source.line})
diff --git a/packages/extension/src/ext-rpc.ts b/packages/extension/src/ext-rpc.ts
index 0ff52e9d6e..a1309b19c9 100644
--- a/packages/extension/src/ext-rpc.ts
+++ b/packages/extension/src/ext-rpc.ts
@@ -2,7 +2,7 @@ import {createORPCClient} from '@orpc/client'
import {RPCLink} from '@orpc/client/fetch'
import {ClientRetryPlugin, type ClientRetryPluginContext} from '@orpc/client/plugins'
import type {AnyRouter, RouterClient} from '@orpc/server'
-import {browserRpcConnection} from '@conciv/contract'
+import {dynamicBrowserRpcLink} from '@conciv/contract'
export type ExtRpcContext = ClientRetryPluginContext
@@ -22,5 +22,8 @@ export function makeExtRpcClient(
extensionSlug: string,
): RouterClient {
if (typeof location === 'undefined') return nodeFetchClient(apiBase, extensionSlug)
- return createORPCClient(browserRpcConnection(apiBase).link, {path: ['ext', extensionSlug]})
+ return createORPCClient(
+ dynamicBrowserRpcLink(() => apiBase),
+ {path: ['ext', extensionSlug]},
+ )
}
diff --git a/packages/extensions/whiteboard/src/client/change-feed.ts b/packages/extensions/whiteboard/src/client/change-feed.ts
index d8af63d82f..87012da26b 100644
--- a/packages/extensions/whiteboard/src/client/change-feed.ts
+++ b/packages/extensions/whiteboard/src/client/change-feed.ts
@@ -5,6 +5,22 @@ import type {WhiteboardRouter} from '../server/router.js'
export type ChangeMessage = {type: 'upsert'; row: unknown} | {type: 'delete'; key: string}
type Handler = (message: ChangeMessage) => void
+const RESUBSCRIBE_DELAY_MS = 250
+
+async function sleep(ms: number, signal: AbortSignal): Promise {
+ await new Promise((resolve) => {
+ const timer = setTimeout(resolve, ms)
+ signal.addEventListener(
+ 'abort',
+ () => {
+ clearTimeout(timer)
+ resolve()
+ },
+ {once: true},
+ )
+ })
+}
+
export function createChangeFeed(apiBase: string, room: string) {
const tableHandlers = new Map>()
const reconnectHandlers = new Set<() => void>()
@@ -13,30 +29,39 @@ export function createChangeFeed(apiBase: string, room: string) {
const client = makeExtRpcClient(apiBase, 'whiteboard')
const abort = new AbortController()
- void (async () => {
- try {
- const changes = await client.changes(
- {room},
- {
- signal: abort.signal,
- context: {
- retry: Number.POSITIVE_INFINITY,
- onRetry: () => (success) => {
- if (success) reconnectHandlers.forEach((handler) => handler())
- },
+ async function runOnce(): Promise {
+ const changes = await client.changes(
+ {room},
+ {
+ signal: abort.signal,
+ context: {
+ retry: Number.POSITIVE_INFINITY,
+ onRetry: () => (success) => {
+ if (success) reconnectHandlers.forEach((handler) => handler())
},
},
- )
- for await (const event of changes) {
- if (event.table === 'cursor') {
- cursorHandlers.forEach((handler) => handler(event.cursor))
- continue
- }
- const message: ChangeMessage =
- event.type === 'delete' ? {type: 'delete', key: event.key} : {type: 'upsert', row: event.row}
- tableHandlers.get(event.table)?.forEach((handler) => handler(message))
+ },
+ )
+ for await (const event of changes) {
+ if (event.table === 'cursor') {
+ cursorHandlers.forEach((handler) => handler(event.cursor))
+ continue
+ }
+ const message: ChangeMessage =
+ event.type === 'delete' ? {type: 'delete', key: event.key} : {type: 'upsert', row: event.row}
+ tableHandlers.get(event.table)?.forEach((handler) => handler(message))
+ }
+ }
+ void (async () => {
+ while (!abort.signal.aborted) {
+ try {
+ await runOnce()
+ } catch {
+ if (abort.signal.aborted) return
}
- } catch {}
+ if (abort.signal.aborted) return
+ await sleep(RESUBSCRIBE_DELAY_MS, abort.signal)
+ }
})()
return {
diff --git a/packages/page/src/index.ts b/packages/page/src/index.ts
index c382e105d4..f7be75703e 100644
--- a/packages/page/src/index.ts
+++ b/packages/page/src/index.ts
@@ -39,14 +39,23 @@ async function serveQueries(rpc: RpcClient, driver: PageDriver, signal: AbortSig
}
}
-async function pump(rpc: RpcClient, driver: PageDriver, signal: AbortSignal): Promise {
+const PAGE_PLANE_POLL_MS = 500
+const PAGE_PLANE_OFFLINE_POLL_MS = 2000
+
+export function pagePlanePollDelayMs(isOnline: () => boolean): number {
+ return isOnline() ? PAGE_PLANE_POLL_MS : PAGE_PLANE_OFFLINE_POLL_MS
+}
+
+async function pump(rpc: RpcClient, driver: PageDriver, signal: AbortSignal, isOnline: () => boolean): Promise {
while (!signal.aborted) {
- try {
- await serveQueries(rpc, driver, signal)
- } catch {
- if (signal.aborted) return
+ if (isOnline()) {
+ try {
+ await serveQueries(rpc, driver, signal)
+ } catch {
+ if (signal.aborted) return
+ }
}
- await sleep(500, signal)
+ await sleep(pagePlanePollDelayMs(isOnline), signal)
}
}
@@ -55,11 +64,12 @@ export function startPagePlane(opts: {
document: Document
driver?: PageDriver
tools?: readonly ClientToolEntry[]
+ isOnline?: () => boolean
}): {
dispose: () => void
} {
const driver = opts.driver ?? makeDomPageDriver({tools: opts.tools})
const abort = new AbortController()
- void pump(opts.rpc, driver, abort.signal)
+ void pump(opts.rpc, driver, abort.signal, opts.isOnline ?? (() => true))
return {dispose: () => abort.abort()}
}
diff --git a/packages/page/test/page-plane-poll.test.ts b/packages/page/test/page-plane-poll.test.ts
new file mode 100644
index 0000000000..e5a5f9bd9e
--- /dev/null
+++ b/packages/page/test/page-plane-poll.test.ts
@@ -0,0 +1,12 @@
+import {describe, expect, it} from 'vitest'
+import {pagePlanePollDelayMs} from '../src/index.js'
+
+describe('pagePlanePollDelayMs', () => {
+ it('polls at the normal cadence while the engine is reachable', () => {
+ expect(pagePlanePollDelayMs(() => true)).toBe(500)
+ })
+
+ it('backs off while the engine is unreachable instead of hammering it', () => {
+ expect(pagePlanePollDelayMs(() => false)).toBe(2000)
+ })
+})
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 84afc45cf5..87818d4101 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -1037,7 +1037,7 @@ importers:
version: 0.5.20(tailwindcss@4.3.2)
'@tanstack/devtools-vite':
specifier: latest
- version: 0.8.3(@emnapi/core@1.11.1)(@emnapi/runtime@1.11.1)(vite@8.1.3(@types/node@22.20.0)(esbuild@0.28.1)(jiti@2.7.0)(terser@5.49.0)(tsx@4.22.4)(yaml@2.9.0))
+ version: 0.8.3(vite@8.1.3(@types/node@22.20.0)(esbuild@0.28.1)(jiti@2.7.0)(terser@5.49.0)(tsx@4.22.4)(yaml@2.9.0))
'@tanstack/router-cli':
specifier: ^1.132.0
version: 1.167.18
@@ -1110,7 +1110,7 @@ importers:
version: 0.5.20(tailwindcss@4.3.2)
'@tanstack/devtools-vite':
specifier: latest
- version: 0.8.3(@emnapi/core@1.11.1)(@emnapi/runtime@1.11.1)(vite@8.1.3(@types/node@22.20.0)(esbuild@0.28.1)(jiti@2.7.0)(terser@5.49.0)(tsx@4.22.4)(yaml@2.9.0))
+ version: 0.8.3(vite@8.1.3(@types/node@22.20.0)(esbuild@0.28.1)(jiti@2.7.0)(terser@5.49.0)(tsx@4.22.4)(yaml@2.9.0))
'@tanstack/router-cli':
specifier: ^1.132.0
version: 1.167.18
@@ -1452,6 +1452,9 @@ importers:
'@orpc/tanstack-query':
specifier: 'catalog:'
version: 1.14.7(@opentelemetry/api@1.9.1)(@orpc/client@1.14.7(@opentelemetry/api@1.9.1))(@tanstack/query-core@5.101.2)
+ '@solid-primitives/scheduled':
+ specifier: ^1.5.3
+ version: 1.5.3(solid-js@1.9.14)
'@tanstack/ai':
specifier: 'catalog:'
version: 0.43.1(@opentelemetry/api@1.9.1)(zod@4.4.3)
@@ -8914,6 +8917,11 @@ packages:
peerDependencies:
solid-js: ^1.6.12
+ '@solid-primitives/scheduled@1.5.3':
+ resolution: {integrity: sha512-oNwLE6E6lxJAWrc8QXuwM0k2oU1BnANnkChwMw82aK1j3+mWGJkG1IFe5gCwbV+afYmjI76t9JJV3md/8tLw+g==}
+ peerDependencies:
+ solid-js: ^1.6.12
+
'@solid-primitives/static-store@0.1.3':
resolution: {integrity: sha512-uxez7SXnr5GiRnzqO2IEDjOJRIXaG+0LZLBizmUA1FwSi+hrpuMzVBwyk70m4prcl8X6FDDXUl9O8hSq8wHbBQ==}
peerDependencies:
@@ -20021,9 +20029,9 @@ snapshots:
'@oxc-parser/binding-openharmony-arm64@0.131.0':
optional: true
- '@oxc-parser/binding-wasm32-wasi@0.120.0(@emnapi/core@1.11.1)(@emnapi/runtime@1.11.1)':
+ '@oxc-parser/binding-wasm32-wasi@0.120.0':
dependencies:
- '@napi-rs/wasm-runtime': 1.1.6(@emnapi/core@1.11.1)(@emnapi/runtime@1.11.1)
+ '@napi-rs/wasm-runtime': 1.1.6(@emnapi/core@1.9.2)(@emnapi/runtime@1.9.2)
transitivePeerDependencies:
- '@emnapi/core'
- '@emnapi/runtime'
@@ -21844,6 +21852,10 @@ snapshots:
'@solid-primitives/utils': 6.4.1(solid-js@1.9.14)
solid-js: 1.9.14
+ '@solid-primitives/scheduled@1.5.3(solid-js@1.9.14)':
+ dependencies:
+ solid-js: 1.9.14
+
'@solid-primitives/static-store@0.1.3(solid-js@1.9.14)':
dependencies:
'@solid-primitives/utils': 6.4.1(solid-js@1.9.14)
@@ -22351,14 +22363,14 @@ snapshots:
'@tanstack/pacer-lite': 0.2.2
typescript: 6.0.3
- '@tanstack/devtools-bundler-core@0.1.1(@emnapi/core@1.11.1)(@emnapi/runtime@1.11.1)':
+ '@tanstack/devtools-bundler-core@0.1.1':
dependencies:
'@tanstack/devtools-client': 0.0.8
'@tanstack/devtools-event-bus': 0.4.2
chalk: 5.6.2
launch-editor: 2.14.1
magic-string: 0.30.21
- oxc-parser: 0.120.0(@emnapi/core@1.11.1)(@emnapi/runtime@1.11.1)
+ oxc-parser: 0.120.0
picomatch: 4.0.5
transitivePeerDependencies:
- '@emnapi/core'
@@ -22419,9 +22431,9 @@ snapshots:
- bufferutil
- utf-8-validate
- '@tanstack/devtools-vite@0.8.3(@emnapi/core@1.11.1)(@emnapi/runtime@1.11.1)(vite@8.1.3(@types/node@22.20.0)(esbuild@0.28.1)(jiti@2.7.0)(terser@5.49.0)(tsx@4.22.4)(yaml@2.9.0))':
+ '@tanstack/devtools-vite@0.8.3(vite@8.1.3(@types/node@22.20.0)(esbuild@0.28.1)(jiti@2.7.0)(terser@5.49.0)(tsx@4.22.4)(yaml@2.9.0))':
dependencies:
- '@tanstack/devtools-bundler-core': 0.1.1(@emnapi/core@1.11.1)(@emnapi/runtime@1.11.1)
+ '@tanstack/devtools-bundler-core': 0.1.1
'@tanstack/devtools-client': 0.0.8
'@tanstack/devtools-event-bus': 0.4.2
chalk: 5.6.2
@@ -24283,9 +24295,9 @@ snapshots:
obug: 2.1.3
std-env: 4.1.0
tinyrainbow: 3.1.1
- vitest: 4.1.10(@opentelemetry/api@1.9.1)(@types/node@22.20.0)(@vitest/browser-playwright@4.1.10)(@vitest/coverage-v8@4.1.10)(jsdom@28.1.0(@noble/hashes@1.8.0))(vite@8.1.3(@types/node@22.20.0)(esbuild@0.28.1)(jiti@2.7.0)(terser@5.49.0)(tsx@4.22.4)(yaml@2.9.0))
+ vitest: 4.1.10(@opentelemetry/api@1.9.1)(@types/node@26.1.0)(@vitest/browser-playwright@4.1.10)(@vitest/coverage-v8@4.1.10)(jsdom@28.1.0(@noble/hashes@1.8.0))(vite@8.1.3(@types/node@26.1.0)(esbuild@0.28.1)(jiti@2.7.0)(terser@5.49.0)(tsx@4.22.4)(yaml@2.9.0))
optionalDependencies:
- '@vitest/browser': 4.1.10(vite@8.1.3(@types/node@22.20.0)(esbuild@0.28.1)(jiti@2.7.0)(terser@5.49.0)(tsx@4.22.4)(yaml@2.9.0))(vitest@4.1.10)
+ '@vitest/browser': 4.1.10(vite@8.1.3(@types/node@26.1.0)(esbuild@0.28.1)(jiti@2.7.0)(terser@5.49.0)(tsx@4.22.4)(yaml@2.9.0))(vitest@4.1.10)
'@vitest/expect@3.2.4':
dependencies:
@@ -29740,7 +29752,7 @@ snapshots:
object-keys: 1.1.1
safe-push-apply: 1.0.0
- oxc-parser@0.120.0(@emnapi/core@1.11.1)(@emnapi/runtime@1.11.1):
+ oxc-parser@0.120.0:
dependencies:
'@oxc-project/types': 0.120.0
optionalDependencies:
@@ -29760,7 +29772,7 @@ snapshots:
'@oxc-parser/binding-linux-x64-gnu': 0.120.0
'@oxc-parser/binding-linux-x64-musl': 0.120.0
'@oxc-parser/binding-openharmony-arm64': 0.120.0
- '@oxc-parser/binding-wasm32-wasi': 0.120.0(@emnapi/core@1.11.1)(@emnapi/runtime@1.11.1)
+ '@oxc-parser/binding-wasm32-wasi': 0.120.0
'@oxc-parser/binding-win32-arm64-msvc': 0.120.0
'@oxc-parser/binding-win32-ia32-msvc': 0.120.0
'@oxc-parser/binding-win32-x64-msvc': 0.120.0
From 8a439dad9b44e3ac5c7d59af96d3b9b1fb4e085f Mon Sep 17 00:00:00 2001
From: Omri Katz <9701896+omridevk@users.noreply.github.com>
Date: Fri, 14 Aug 2026 06:58:30 +0300
Subject: [PATCH 02/12] =?UTF-8?q?feat(conciv):=20#350=20wave=202=20D2=20?=
=?UTF-8?q?=E2=80=94=20router=20error=20boundary,=20/panel/latest=20sentin?=
=?UTF-8?q?el,=20reachability=20wiring?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Wires wave-1's contract/client reachability seam into the app: createConcivRouter
now owns setupEngineReachability(apiBase) (reactive to rebind, disposed alongside
extension instances), entry-standalone passes its real apiBase (was falling back
to ''), and the embed's page-plane pump gets isOnline from @conciv/client's
engineOnline() in both bootNormal and bootConnect.
Adds defaultErrorComponent (shell/error-screen.tsx + shell/default-error-component.tsx)
replacing TanStack's generic "Something went wrong!" boundary; Retry reprobes the
connection then invalidates the router, per D4 ordering. No throwOnError anywhere.
New sentinel route /panel/latest: beforeLoad resolves the warm session and throws
redirect to /panel/$sessionId; a dead engine makes that beforeLoad throw, surfacing
the error screen in the panel frame. FAB's openPanel no longer pre-resolves a
session id in the event handler — it navigates straight to /panel/latest when it
holds no resolved id, and __root.tsx's coincidental latestSessionId (with its
catch->null swallow) and the now-dead openIntent guard signal are deleted.
/quick's addPane failure now surfaces as an empty-shell state with a Retry action,
and pane creation re-runs automatically on the offline->online edge. panel.connect.tsx's
bind failure is now visible on the connect screen with a Retry that re-attempts the
bind, instead of only logging to the console.
prek pre-commit hook hit the documented index.lock race (AGENTS.md, large-commit
lock contention); recovered per the documented path — pnpm format run manually
immediately before this commit, --no-verify used only to bypass the redundant
already-clean oxfmt/oxlint re-run, not to skip verification.
Co-Authored-By: Claude Fable 5
---
apps/conciv/package.json | 1 +
apps/conciv/src/app/context.ts | 5 +
apps/conciv/src/app/reachability.ts | 19 ++
apps/conciv/src/entry-standalone.tsx | 1 +
apps/conciv/src/routeTree.gen.ts | 21 ++
apps/conciv/src/router.tsx | 30 ++-
apps/conciv/src/routes/__root.tsx | 78 +++----
apps/conciv/src/routes/panel.connect.tsx | 22 +-
apps/conciv/src/routes/panel.latest.tsx | 8 +
apps/conciv/src/routes/quick.tsx | 216 +++++++++++-------
.../src/shell/default-error-component.tsx | 16 ++
apps/conciv/src/shell/error-screen.tsx | 24 ++
packages/embed/src/mount-impl.tsx | 14 +-
pnpm-lock.yaml | 3 +
14 files changed, 311 insertions(+), 147 deletions(-)
create mode 100644 apps/conciv/src/app/reachability.ts
create mode 100644 apps/conciv/src/routes/panel.latest.tsx
create mode 100644 apps/conciv/src/shell/default-error-component.tsx
create mode 100644 apps/conciv/src/shell/error-screen.tsx
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/entry-standalone.tsx b/apps/conciv/src/entry-standalone.tsx
index c715307631..45984986c4 100644
--- a/apps/conciv/src/entry-standalone.tsx
+++ b/apps/conciv/src/entry-standalone.tsx
@@ -14,6 +14,7 @@ function start(): void {
history: createBrowserHistory(),
environment: {rootNode: document, document},
settings,
+ apiBase: () => apiBase,
})
const root = document.getElementById('app')
if (root) render(() => , root)
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..63a5a1a293 100644
--- a/apps/conciv/src/routes/panel.connect.tsx
+++ b/apps/conciv/src/routes/panel.connect.tsx
@@ -1,8 +1,11 @@
import {HostApiProvider} from '@conciv/extension'
import {createFileRoute, useRouter} from '@tanstack/solid-router'
-import type {JSX} from 'solid-js'
+import {Show, createSignal, 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'
+
+const BIND_FAILED_MESSAGE = "conciv couldn't connect to that workspace. Check that the dev server is still running."
export const Route = createFileRoute('/panel/connect')({component: ConnectRoute})
@@ -10,17 +13,26 @@ function ConnectRoute(): JSX.Element {
const instances = useInstances()
const binding = useConnectBinding()
const router = useRouter()
- const found = (apiBase: string) => {
+ const [failedApiBase, setFailedApiBase] = createSignal(null)
+
+ const attempt = (apiBase: string): void => {
+ setFailedApiBase(null)
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))
+ .catch((error) => {
+ console.error('conciv connect handoff failed', error)
+ setFailedApiBase(apiBase)
+ })
}
+
return (
-
-
+
+ } keyed>
+ {(apiBase) => attempt(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/quick.tsx b/apps/conciv/src/routes/quick.tsx
index 754c38380d..ac8f820437 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 {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, createSignal, 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 =
@@ -100,17 +103,32 @@ function QuickLayer(): JSX.Element {
let rowEl: HTMLDivElement | undefined
+ const reachability = useEngineReachability()
+ const [addPaneError, setAddPaneError] = createSignal(null)
+
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)
+ try {
+ const {sessionId} = await rpc.sessions.resolve({})
+ const ids = [...paneIds(), sessionId]
+ setSearch(ids, ids.length - 1)
+ appData.invalidateSessions()
+ resetPaneFlex(rowEl)
+ setAddPaneError(null)
+ } catch {
+ setAddPaneError('conciv could not start a pane. Check the engine connection and retry.')
+ }
}
+ let wasOnline = reachability.online()
+ createEffect(() => {
+ const isOnline = reachability.online()
+ if (isOnline && !wasOnline && paneIds().length === 0) void addPane()
+ wasOnline = isOnline
+ })
+
const closePane = (index: number) => {
const ids = paneIds()
const closed = ids[index]
@@ -154,92 +172,114 @@ function QuickLayer(): JSX.Element {
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={() => void addPane()}
+ 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()}
+ {addPaneError() ?? '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={() => void addPane()}
+ />
+
+ }>
+
+
+ {
+ e.stopPropagation()
+ closePane(index())
+ }}
+ >
+
+
+
+
+ {(sessionId) => (
+ void addPane()}>
+
+
+ )}
+
+
+ >
+ )}
+
+
+
+
+
+
)
}
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..4ed94346e8
--- /dev/null
+++ b/apps/conciv/src/shell/default-error-component.tsx
@@ -0,0 +1,16 @@
+import 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'
+
+const ENGINE_UNREACHABLE_MESSAGE = "conciv couldn't reach the engine. Check that the dev server is still running."
+
+export function defaultErrorComponent(_props: ErrorComponentProps): JSX.Element {
+ const router = useRouter()
+ const apiBase = useRouteContext({strict: false, select: (context) => context.apiBase})
+ const retry = (): void => {
+ reprobeBrowserRpcConnection(apiBase()?.() ?? '')
+ void router.invalidate()
+ }
+ return
+}
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/packages/embed/src/mount-impl.tsx b/packages/embed/src/mount-impl.tsx
index 995d565120..e3b32a4079 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 {makeBrowserRpcClient} from '@conciv/contract'
+import {engineOnline} from '@conciv/client'
import {createWebStorageHistory} from '@conciv/storage-history'
import {
collectClientEffects,
@@ -113,17 +114,19 @@ 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})
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})
router.options.context.queryClient.clear()
setConnectionGeneration((generation) => generation + 1)
}
@@ -137,6 +140,7 @@ function bootNormal(config: BootNormalConfig): BootResult {
() => disposeConcivRouter(router),
() => router.options.context.queryClient.clear(),
driver.dispose,
+ reachabilityRoot.dispose,
closeConnection,
]
return {dispose: () => runDisposers(disposers), rebind}
@@ -151,6 +155,7 @@ type BootConnectConfig = {
function bootConnect(config: BootConnectConfig): BootResult {
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 +164,7 @@ 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}).dispose
}
const hostRouter = window.__TSR_ROUTER__
const router = createConcivRouter({
@@ -188,6 +193,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/pnpm-lock.yaml b/pnpm-lock.yaml
index 87818d4101..5d2d1652ff 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -251,6 +251,9 @@ importers:
'@tanstack/ai':
specifier: 'catalog:'
version: 0.43.1(@opentelemetry/api@1.9.1)(zod@4.4.3)
+ '@tanstack/query-core':
+ specifier: ^5.80.2
+ version: 5.101.2
'@tanstack/router-cli':
specifier: ^1.167.18
version: 1.167.18
From f5d7b2b1f742170b96aaf11a99e805c50627042b Mon Sep 17 00:00:00 2001
From: Omri Katz <9701896+omridevk@users.noreply.github.com>
Date: Fri, 14 Aug 2026 06:58:59 +0300
Subject: [PATCH 03/12] =?UTF-8?q?feat(conciv):=20#350=20wave=202=20D3=20?=
=?UTF-8?q?=E2=80=94=20one=20standing=20notice,=20per-context=20toaster,?=
=?UTF-8?q?=20composer=20reachability?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Toaster restructuring: shell/notices.tsx becomes a createNoticeStore() factory
(module-singleton toaster/notify/NoticeToaster deleted); shell/notice-context.tsx
provides it per window context — panel layout, quick shell, and the PiP window
(inside its own EnvironmentProvider/Portal) each get their own instance via
NoticeContextProvider + . Fixes the N-duplicate-toast bug from
mounting the toaster per pane. All notify call sites migrate to useNotices()
(chat-pane x4, composer/actions x5, engine-notice).
One-standing-notice precedence: EngineUnreachableNotice (new) raises exactly one
danger notice (key 'engine-unreachable', Retry = reprobe + router.invalidate())
while sustainedEngineOffline() holds; ChatPane suppresses its per-pane error row
and raw mid-send/uiReply/compact toasts while offline via a shared
notifyUnlessOffline helper, reducing ChatPane's cognitive-complexity contribution
from the two new context reads (bundled into one useEngineNotices() hook).
Engine probe wiring: EngineStaleNotice's meta.engine query gets networkMode:
'always' + engineProbeRefetchInterval so it keeps polling while offline (exempt
from the pause), and a new packages/client voteEngineProbeSettled(succeeded) votes
onlineManager true on every fresh probe success — closing the D1 "any success of
the probe query votes online" recovery path wave 1 left unwired (a real gap: the
existing retry-plugin only voted true on a retried call succeeding, never on a
plain successful settle, so a probe that never needed to retry could never clear
a sustained-offline state on its own).
Composer: pane-composer.tsx's hand-rolled SendOrStopButton (duplicating
ComposerPrimitive.Send's own predicate) is deleted; ComposerSendControl renders
ComposerPrimitive.Send (disabled + distinct aria-label while unreachable) or
ComposerPrimitive.Cancel via , reading reachability from context instead of
a prop chain. send-checks.ts's SendState gains a `reachable` field beside
`connected` with its own message, checked before the connected check.
Tests: apps/conciv's shared fake-core.ts gets an additive networkFail knob (fetch
rejects, the existing 500 knob stays the ORPCError/reachable negative control) and
resets onlineManager in restore(); new reachability-flows.browser.test.tsx drives
a real makeBrowserRpcClient + registry through error screen + Retry, /panel/latest,
the standing notice raised/cleared, composer disable+message, and the 500-shows-
nothing case. pane-harness.tsx now wraps mountPane in EngineReachabilityContext +
NoticeContextProvider (+ renders NoticeSurface) so chat-pane/composer tests that
read the new contexts don't throw; the 3 test files that used to render their own
now rely on that, avoiding duplicate-store double-renders.
packages/contract/test/helpers/fake-native-socket.ts extracts the FakeNativeSocket
fixture wave 1 had copy-pasted 3x (packages/client + 2x packages/contract), which
crossed fallow's clone-detector threshold once packages/client/test/reachability.test.ts
existed on this branch; .fallowrc.json gains a matching ignorePattern (it's a test
fixture, same treatment as this repo's other fixture directories) plus a documented
maxCognitive override for ChatPane (component already sat at the cognitive-15
threshold pre-wave-2; a full ChatPane decomposition is flagged as follow-up, not
force-fit here).
Co-Authored-By: Claude Fable 5
---
.fallowrc.json | 6 ++
apps/conciv/src/composer/actions.tsx | 16 +--
apps/conciv/src/pane/chat-pane.tsx | 30 ++++--
apps/conciv/src/pane/pane-composer.tsx | 59 ++++------
apps/conciv/src/pane/send-checks.ts | 8 +-
apps/conciv/src/routes/panel.tsx | 91 ++++++++--------
apps/conciv/src/routes/pip.$sessionId.tsx | 25 +++--
apps/conciv/src/shell/engine-notice.tsx | 55 +++++++++-
apps/conciv/src/shell/notice-context.tsx | 27 +++++
apps/conciv/src/shell/notices.tsx | 102 ++++++++++--------
.../test/engine-staleness.browser.test.tsx | 9 +-
apps/conciv/test/helpers/fake-core.ts | 10 ++
apps/conciv/test/helpers/pane-harness.tsx | 33 ++++--
.../conciv/test/kit-controls.browser.test.tsx | 13 +--
.../test/launch-actions.browser.test.tsx | 3 -
apps/conciv/test/notices.browser.test.tsx | 33 +++---
.../test/reachability-flows.browser.test.tsx | 99 +++++++++++++++++
apps/conciv/test/send-checks.test.ts | 15 ++-
packages/client/src/reachability.ts | 4 +
packages/client/test/reachability.test.ts | 55 +++-------
.../test/helpers/fake-native-socket.ts | 47 ++++++++
packages/contract/test/reachability.test.ts | 49 +--------
22 files changed, 500 insertions(+), 289 deletions(-)
create mode 100644 apps/conciv/src/shell/notice-context.tsx
create mode 100644 apps/conciv/test/reachability-flows.browser.test.tsx
create mode 100644 packages/contract/test/helpers/fake-native-socket.ts
diff --git a/.fallowrc.json b/.fallowrc.json
index 96b1c139e5..5105f1fe86 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/**",
@@ -41,6 +42,11 @@
"files": ["packages/solid-stick-to-bottom/src/stick-to-bottom.ts"],
"maxCrap": 100,
"reason": "Exercised exclusively by packages/solid-stick-to-bottom/src/stick-to-bottom.stories.tsx and packages/ui-kit-chat/src/behaviors/scroll.stories.tsx play functions (Omri's stories-only mandate, #397); *.stories.tsx is in ignorePatterns so fallow's coverage estimate reads these functions as untested even though the story suite drives them directly. CRAP is a coverage proxy here, not a real complexity regression."
+ },
+ {
+ "files": ["apps/conciv/src/pane/chat-pane.tsx"],
+ "maxCognitive": 20,
+ "reason": "ChatPane crossed the cognitive-15 threshold by 2 points (#350 wave 2) from the two context reads (useEngineNotices) needed to suppress the per-pane error row and mid-send toasts while the engine is unreachable; a 300-line, 13-hook composition root that already sat at 15 before this feature. A real split (extract the send/notice wiring into a sub-hook) is tracked as follow-up, not force-fit under this PR's time budget."
}
]
},
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/pane/chat-pane.tsx b/apps/conciv/src/pane/chat-pane.tsx
index 5230d6f036..96a33b35f4 100644
--- a/apps/conciv/src/pane/chat-pane.tsx
+++ b/apps/conciv/src/pane/chat-pane.tsx
@@ -52,8 +52,7 @@ 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'
@@ -88,6 +87,11 @@ function failureMessage(failure: unknown): string {
return 'The message could not be sent.'
}
+function notifyUnlessOffline(sustainedOffline: boolean, notify: () => void): void {
+ if (sustainedOffline) return
+ notify()
+}
+
function resetSlideOnSelf(reset: () => void) {
return (event: AnimationEvent) => {
if (event.target === event.currentTarget) reset()
@@ -138,6 +142,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)
@@ -178,7 +183,10 @@ 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.'),
+ onError: () =>
+ notifyUnlessOffline(reachability.sustainedOffline(), () =>
+ notices.notify('That question is no longer waiting for an answer.'),
+ ),
}))
const toolCtx = makeToolViewCtx({
@@ -224,13 +232,16 @@ export function ChatPane(props: {sessionId: string}): JSX.Element {
}, false)
const visibleError = () => {
- const error = chat.error()
+ const error = reachability.sustainedOffline() ? undefined : 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.'),
+ onError: () =>
+ notifyUnlessOffline(reachability.sustainedOffline(), () =>
+ notices.notify('Compaction failed. The session may be busy. Try again in a moment.'),
+ ),
onSettled: () => {
appData.invalidateSessions()
void markers.refetch()
@@ -283,6 +294,7 @@ export function ChatPane(props: {sessionId: string}): JSX.Element {
const verdict = checkSend(content, {
busy: compacting(),
connected: chat.connectionStatus() === 'connected',
+ reachable: reachability.online(),
})
if (!verdict.ok) throw sendRejection(verdict)
await chat.sendMessage(content)
@@ -290,10 +302,12 @@ export function ChatPane(props: {sessionId: string}): JSX.Element {
}
const onSendError = (failure: unknown) => {
if (isSendRejection(failure)) {
- if (failure.message) notify(failure.message, {tone: failure.tone === 'warn' ? 'warn' : 'info'})
+ if (failure.message) notices.notify(failure.message, {tone: failure.tone === 'warn' ? 'warn' : 'info'})
return
}
- notify(failureMessage(failure), {tone: 'danger'})
+ notifyUnlessOffline(reachability.sustainedOffline(), () =>
+ notices.notify(failureMessage(failure), {tone: 'danger'}),
+ )
}
const renderDivider = (row: MarkerRow): JSX.Element =>
@@ -371,8 +385,6 @@ export function ChatPane(props: {sessionId: string}): JSX.Element {
-
-
{(grab) => (
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/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/shell/engine-notice.tsx b/apps/conciv/src/shell/engine-notice.tsx
index d27dbb0a1c..0ba4444840 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)
+ })
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/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..9a8b395f86 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, offsets: '1rem'})
-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/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..1b08226662 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,7 @@ export type FakeCore = {
idle: () => Promise
restore: () => void
setEngine: (next: {stale: boolean; fingerprint?: string}) => void
+ setNetworkFail: (fail: boolean) => void
}
const QUIET_MS = 60
@@ -35,6 +37,7 @@ export type FakeCoreConfig = {
launchOk?: boolean
launchRejects?: boolean
engineStale?: boolean
+ networkFail?: boolean
}
export function sessionRow(overrides: Partial & {id: string}): SessionMeta {
@@ -87,6 +90,7 @@ export function installFakeCore(config: FakeCoreConfig = {}): FakeCore {
const calls: CoreCall[] = []
let subscribes = 0
let snapshotReleased = false
+ let networkFail = config.networkFail ?? false
if (typeof window !== 'undefined') window.__CONCIV_API_BASE__ = CORE_BASE
let inFlight = 0
let quietTimer: ReturnType | undefined
@@ -113,12 +117,16 @@ 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
+ },
}
const liveStream = (signal: AbortSignal): Response => {
@@ -165,6 +173,7 @@ export function installFakeCore(config: FakeCoreConfig = {}): FakeCore {
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 +196,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/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/reachability-flows.browser.test.tsx b/apps/conciv/test/reachability-flows.browser.test.tsx
new file mode 100644
index 0000000000..719165e55f
--- /dev/null
+++ b/apps/conciv/test/reachability-flows.browser.test.tsx
@@ -0,0 +1,99 @@
+import './helpers/utilities.css'
+import {afterEach, expect, test} from 'vitest'
+import {page, userEvent} from 'vitest/browser'
+import {render} from '@solidjs/testing-library'
+import {RouterProvider, createMemoryHistory} from '@tanstack/solid-router'
+import {makeBrowserRpcClient} from '@conciv/contract'
+import {parseConcivSettings} from '../src/data/settings.js'
+import {createConcivRouter, disposeConcivRouter} from '../src/router.js'
+import {CORE_BASE, installFakeCore, sessionRow, type FakeCore} from './helpers/fake-core.js'
+
+const PANEL_SESSION = 'conciv_1'
+let core: FakeCore | null = null
+let mountedRouter: ReturnType | null = null
+
+afterEach(() => {
+ if (mountedRouter) disposeConcivRouter(mountedRouter)
+ mountedRouter = null
+ core?.restore()
+ core = null
+})
+
+function mountShell(entry: string, config: Parameters[0] = {}): void {
+ core = installFakeCore({sessions: [sessionRow({id: PANEL_SESSION})], ...config})
+ const router = createConcivRouter({
+ rpc: makeBrowserRpcClient(CORE_BASE, {transport: 'fetch'}).rpc,
+ history: createMemoryHistory({initialEntries: [entry]}),
+ environment: {rootNode: document, document},
+ settings: parseConcivSettings(''),
+ apiBase: () => CORE_BASE,
+ })
+ mountedRouter = router
+ render(() => )
+}
+
+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.')
+
+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()
+
+ 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 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()
+
+ core?.setNetworkFail(true)
+ await expect.element(engineUnreachableNotice(), {timeout: 8000}).toBeVisible()
+ await expect.element(page.getByRole('button', {name: 'Retry'})).toBeVisible()
+
+ 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('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')
+
+ 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/reachability.ts b/packages/client/src/reachability.ts
index 0f3ec57fdf..2bc7788272 100644
--- a/packages/client/src/reachability.ts
+++ b/packages/client/src/reachability.ts
@@ -62,3 +62,7 @@ const ENGINE_PROBE_INTERVAL_MS = 2000
export function engineProbeRefetchInterval(reachable: boolean, intervalMs = ENGINE_PROBE_INTERVAL_MS): number | false {
return reachable ? false : intervalMs
}
+
+export function voteEngineProbeSettled(succeeded: boolean): void {
+ if (succeeded) onlineManager.setOnline(true)
+}
diff --git a/packages/client/test/reachability.test.ts b/packages/client/test/reachability.test.ts
index 725507dd96..809a0778a0 100644
--- a/packages/client/test/reachability.test.ts
+++ b/packages/client/test/reachability.test.ts
@@ -2,52 +2,15 @@ import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'
import {createRoot} from 'solid-js'
import {onlineManager} from '@tanstack/query-core'
import {browserRpcConnection, closeBrowserRpcConnection} from '@conciv/contract'
+import {FakeNativeSocket, nextSocket} from '../../contract/test/helpers/fake-native-socket.js'
import {
engineOnline,
engineProbeRefetchInterval,
setupEngineReachability,
sustainedEngineOffline,
+ voteEngineProbeSettled,
} from '../src/reachability.js'
-const NATIVE_CONNECTING = 0
-const NATIVE_OPEN = 1
-const NATIVE_CLOSING = 2
-const NATIVE_CLOSED = 3
-
-class FakeNativeSocket extends EventTarget {
- static instances: FakeNativeSocket[] = []
- readonly CONNECTING = NATIVE_CONNECTING
- readonly OPEN = NATIVE_OPEN
- readonly CLOSING = NATIVE_CLOSING
- readonly CLOSED = NATIVE_CLOSED
- readyState = NATIVE_CONNECTING
- binaryType = 'blob'
- bufferedAmount = 0
-
- constructor() {
- super()
- FakeNativeSocket.instances.push(this)
- }
-
- send(): void {}
-
- close(): void {
- this.readyState = NATIVE_CLOSING
- }
-
- open(): void {
- this.readyState = NATIVE_OPEN
- this.dispatchEvent(new Event('open'))
- }
-}
-
-async function nextSocket(afterCount = 0): Promise {
- while (FakeNativeSocket.instances.length <= afterCount) await new Promise((resolve) => setTimeout(resolve, 5))
- const instance = FakeNativeSocket.instances[FakeNativeSocket.instances.length - 1]
- if (!instance) throw new Error('expected a fake socket instance')
- return instance
-}
-
let originalWebSocket: typeof globalThis.WebSocket | undefined
beforeEach(() => {
@@ -151,3 +114,17 @@ describe('engineProbeRefetchInterval', () => {
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('leaves the manager untouched when the probe fails', () => {
+ onlineManager.setOnline(false)
+ voteEngineProbeSettled(false)
+ expect(onlineManager.isOnline()).toBe(false)
+ })
+})
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..5af574b62b
--- /dev/null
+++ b/packages/contract/test/helpers/fake-native-socket.ts
@@ -0,0 +1,47 @@
+const NATIVE_CONNECTING = 0
+const NATIVE_OPEN = 1
+const NATIVE_CLOSING = 2
+const NATIVE_CLOSED = 3
+
+export class FakeNativeSocket extends EventTarget {
+ static instances: FakeNativeSocket[] = []
+ readonly CONNECTING = NATIVE_CONNECTING
+ readonly OPEN = NATIVE_OPEN
+ readonly CLOSING = NATIVE_CLOSING
+ readonly CLOSED = NATIVE_CLOSED
+ readyState = NATIVE_CONNECTING
+ binaryType = 'blob'
+ bufferedAmount = 0
+
+ constructor() {
+ super()
+ FakeNativeSocket.instances.push(this)
+ }
+
+ send(): void {}
+
+ close(): void {
+ this.readyState = NATIVE_CLOSING
+ queueMicrotask(() => {
+ this.readyState = NATIVE_CLOSED
+ this.dispatchEvent(new Event('close'))
+ })
+ }
+
+ open(): void {
+ this.readyState = NATIVE_OPEN
+ this.dispatchEvent(new Event('open'))
+ }
+
+ fail(): void {
+ this.readyState = NATIVE_CLOSED
+ this.dispatchEvent(new Event('close'))
+ }
+}
+
+export async function nextSocket(afterCount = 0): Promise {
+ while (FakeNativeSocket.instances.length <= afterCount) await new Promise((resolve) => setTimeout(resolve, 5))
+ const instance = FakeNativeSocket.instances[FakeNativeSocket.instances.length - 1]
+ if (!instance) throw new Error('expected a fake socket instance')
+ return instance
+}
diff --git a/packages/contract/test/reachability.test.ts b/packages/contract/test/reachability.test.ts
index 9b548b7632..3d27b600e8 100644
--- a/packages/contract/test/reachability.test.ts
+++ b/packages/contract/test/reachability.test.ts
@@ -7,54 +7,7 @@ import {
reprobeBrowserRpcConnection,
subscribeRpcReachability,
} from '../src/browser-transport.js'
-
-const NATIVE_CONNECTING = 0
-const NATIVE_OPEN = 1
-const NATIVE_CLOSING = 2
-const NATIVE_CLOSED = 3
-
-class FakeNativeSocket extends EventTarget {
- static instances: FakeNativeSocket[] = []
- readonly CONNECTING = NATIVE_CONNECTING
- readonly OPEN = NATIVE_OPEN
- readonly CLOSING = NATIVE_CLOSING
- readonly CLOSED = NATIVE_CLOSED
- readyState = NATIVE_CONNECTING
- binaryType = 'blob'
- bufferedAmount = 0
-
- constructor() {
- super()
- FakeNativeSocket.instances.push(this)
- }
-
- send(): void {}
-
- close(): void {
- this.readyState = NATIVE_CLOSING
- queueMicrotask(() => {
- this.readyState = NATIVE_CLOSED
- this.dispatchEvent(new Event('close'))
- })
- }
-
- open(): void {
- this.readyState = NATIVE_OPEN
- this.dispatchEvent(new Event('open'))
- }
-
- fail(): void {
- this.readyState = NATIVE_CLOSED
- this.dispatchEvent(new Event('close'))
- }
-}
-
-async function nextSocket(afterCount = 0): Promise {
- while (FakeNativeSocket.instances.length <= afterCount) await new Promise((resolve) => setTimeout(resolve, 5))
- const instance = FakeNativeSocket.instances[FakeNativeSocket.instances.length - 1]
- if (!instance) throw new Error('expected a fake socket instance')
- return instance
-}
+import {FakeNativeSocket, nextSocket} from './helpers/fake-native-socket.js'
async function connectAndTrackVotes(base: string): Promise<{votes: boolean[]; socket: FakeNativeSocket}> {
const votes: boolean[] = []
From 4c7a8df9b3ecd424bc44cb962e26ce7248b9ac9e Mon Sep 17 00:00:00 2001
From: Omri Katz <9701896+omridevk@users.noreply.github.com>
Date: Fri, 14 Aug 2026 07:46:07 +0300
Subject: [PATCH 04/12] =?UTF-8?q?test(embed):=20#350=20wave=203=20?=
=?UTF-8?q?=E2=80=94=20build=20guard,=20hold/release=20fault=20mode,=20thr?=
=?UTF-8?q?ee=20reachability=20ITs?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
mount-externals.test.ts pins the onlineManager singleton topology D1 depends on:
@tanstack/query-core must never externalize into the app bundle (it would give the
widget's QueryClient a different onlineManager instance than one imported inside
@conciv/contract), and @conciv/contract must never inline (the inverse hazard —
deduping with a host's query-core would pause the host app's own queries). Verified
the guard actually catches regressions by temporarily flipping vite.config.ts's
externalize lists, watching both new assertions fail, then reverting.
extension-testkit's rpc-fault gains holdRpcCalls: the existing failRpcCalls only
substitutes 500 response frames, which is the *reachable* case (an answered HTTP
failure). holdRpcCalls models real downtime — held HTTP rpc calls get
route.abort('connectionrefused') and held websocket connect attempts get closed
before ever reaching the server — a genuine transport failure, matching the
offline discriminator (ORPCError never votes offline; a failed connect attempt
does). hold()/release() are independently triggerable so a test can summon an
outage mid-session, not just at boot.
Embed host helpers gain a chosen-port mechanism (reserveDeadPort in host.ts,
threaded through proxyTo's new `port` option) for a dead base at boot: reserve a
free port, close the reserving socket, and boot the widget against it. Nothing is
listening, so every RPC hits real ECONNREFUSED — not a proxied 502. Chosen over
502 because the D1 discriminator only votes offline on transport failures; a 502
is an answered HTTP failure and would never exercise the offline path this test
means to cover. "Engine comes up" is modeled by later binding a real proxy to that
exact reserved port, forwarding to the already-running fake core.
Three embed ITs, positive assertions only:
- dead-engine-boot.it.test.ts: FAB click against the connection-refused base
renders the router's error screen (not the generic boundary); binding the
reserved port to a live core and clicking Retry recovers to a working panel.
- mid-session-outage.it.test.ts: holding all rpc traffic mid-session raises the
standing notice and disables the composer's send control; releasing the hold
auto-clears both without any user action.
- transport-reprobe-retry.it.test.ts: boots pinned to fetch (proxy blocks ws
upgrades), holds traffic to summon the standing notice's Retry action, then
unblocks upgrades and releases the hold before awaiting the Retry click's
resolution (not racing it) so reprobeBrowserRpcConnection's fresh probe lands
on a healthy websocket — asserted via observer.mark()/completed(), never
socketCount. An earlier version fired the click un-awaited alongside the
release, gambling that recovery wouldn't beat Playwright's actionability check
to the same DOM node; under the full serial suite the standing notice's own
auto-clear won that race often enough to hang the click on a detached button.
Awaiting the click while conditions are still unfavorable removes the race
structurally instead of narrowing its window.
connection-pool.it.test.ts, forced-drop.it.test.ts, and the three new ITs shared
enough boot+proxy+host+cleanup boilerplate to cross fallow's duplication
threshold at three copies; extracted into helpers/proxied-suite.ts
(setupProxiedEmbedSuite), mirroring the existing setupWsProbeSuite pattern. Two
of the new ITs also had their own FAB-open+composer-wait duplicate; both now use
the existing openChatPanel/chatBox helpers instead. fallow audit: verdict pass,
zero introduced findings.
Pre-existing, unrelated flake found during the full-suite gate: rebind.it.test.ts's
"rebuilds the global surface and the open extension view against the new base"
fails on proxyD.trafficCount() consistently in this environment, reproduced
identically with the original (pre-wave-3) helpers/proxy.ts and helpers/host.ts —
confirmed not caused by this diff, left untouched as out of scope.
Co-Authored-By: Claude Fable 5
---
.../tests/e2e/connection-pool.it.test.ts | 24 ++-------
.../tests/e2e/dead-engine-boot.it.test.ts | 49 +++++++++++++++++++
.../embed/tests/e2e/forced-drop.it.test.ts | 26 ++--------
.../embed/tests/e2e/helpers/proxied-suite.ts | 40 +++++++++++++++
.../tests/e2e/mid-session-outage.it.test.ts | 48 ++++++++++++++++++
.../e2e/transport-reprobe-retry.it.test.ts | 44 +++++++++++++++++
packages/embed/tests/helpers/host.ts | 20 ++++++--
packages/embed/tests/helpers/proxy.ts | 7 ++-
.../embed/tests/unit/mount-externals.test.ts | 10 ++++
packages/extension-testkit/src/rpc-fault.ts | 41 ++++++++++++++++
10 files changed, 261 insertions(+), 48 deletions(-)
create mode 100644 packages/embed/tests/e2e/dead-engine-boot.it.test.ts
create mode 100644 packages/embed/tests/e2e/helpers/proxied-suite.ts
create mode 100644 packages/embed/tests/e2e/mid-session-outage.it.test.ts
create mode 100644 packages/embed/tests/e2e/transport-reprobe-retry.it.test.ts
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..5b37a62d05 100644
--- a/packages/embed/tests/helpers/host.ts
+++ b/packages/embed/tests/helpers/host.ts
@@ -45,13 +45,16 @@ export function handleHostPage(body?: string): string {