Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/connection-error-handling.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@conciv/contract': patch
---

Global engine-reachability handling: reachability seam + single rebindable rpc client factory in contract, router error boundary with /panel/latest sentinel, one standing offline notice per window context, composer send disabled while unreachable.
1 change: 1 addition & 0 deletions .fallowrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -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/**",
Expand Down
1 change: 1 addition & 0 deletions apps/conciv/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
5 changes: 5 additions & 0 deletions apps/conciv/src/app/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ export type AppContextValue = {
disconnect?: () => void
grabProvider?: GrabProvider
connectionGeneration: () => number
apiBase: () => string
}

export const AppContext = createContext<AppContextValue>()
Expand Down Expand Up @@ -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)
}
19 changes: 19 additions & 0 deletions apps/conciv/src/app/reachability.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import {createContext, useContext, type Accessor} from 'solid-js'
import {engineOnline, sustainedEngineOffline} from '@conciv/client'

export type EngineReachability = {
online: Accessor<boolean>
sustainedOffline: Accessor<boolean>
}

export const EngineReachabilityContext = createContext<EngineReachability>()

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
}
16 changes: 9 additions & 7 deletions apps/conciv/src/composer/actions.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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'

Expand All @@ -26,7 +27,7 @@ function errorCode(error: unknown): string | null {
return null
}

async function copyCommand(command: string): Promise<void> {
async function copyCommand(notify: Notify, command: string): Promise<void> {
try {
await navigator.clipboard.writeText(command)
notify('Command copied. Paste it in your terminal.')
Expand All @@ -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())
Expand Down Expand Up @@ -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 (
Expand Down
3 changes: 2 additions & 1 deletion apps/conciv/src/entry-standalone.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,11 @@ function start(): void {
const apiBase = params.get('core') ?? ''
window.__CONCIV_API_BASE__ = apiBase
const router = createConcivRouter({
rpc: makeBrowserRpcClient(apiBase, {transport: settings.transport}),
rpc: makeBrowserRpcClient(apiBase, {transport: settings.transport}).rpc,
history: createBrowserHistory(),
environment: {rootNode: document, document},
settings,
apiBase: () => apiBase,
})
const root = document.getElementById('app')
if (root) render(() => <RouterProvider router={router} />, root)
Expand Down
85 changes: 21 additions & 64 deletions apps/conciv/src/pane/chat-pane.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import {
untrack,
type JSX,
} from 'solid-js'
import {useMutation, useQuery} from '@tanstack/solid-query'
import {useQuery} from '@tanstack/solid-query'
import {useChatSession} from '@conciv/client'
import {
AttachmentByMime,
Expand All @@ -30,9 +30,8 @@ import {PAGE_ACT_TOOL_NAMES, PAGE_TOOL_PREFIX} from '@conciv/extension-page/defs
import {builtinToolCards, nowTitle} from '@conciv/ui-kit-chat-tools'
import {concivToolCards} from '@conciv/tools/cards'
import {coreToolCards} from '@conciv/core/cards'
import type {MessagePart, MultimodalContent, ToolCallPart, ToolResultPart} from '@tanstack/ai-client'
import type {MessagePart, ToolCallPart, ToolResultPart} from '@tanstack/ai-client'
import type {ToolCardEntry, ToolCatalogView} from '@conciv/protocol/tool-view-types'
import type {UiAnswerValue} from '@conciv/protocol/ui-types'
import type {MarkerRow} from '@conciv/contract'
import {collectToolRenderers, HostApiProvider} from '@conciv/extension'
import type {Grab} from '@conciv/grab'
Expand All @@ -52,14 +51,13 @@ import {ExtensionSurface} from '../extension/extension-slots.js'
import {makePaneGrabApi} from '../extension/pane-grab.js'
import {ComposerActions} from '../composer/actions.js'
import {SessionModelSelector} from '../composer/model-selector.js'
import {NoticeToaster, notify} from '../shell/notices.js'
import {EngineStaleNotice} from '../shell/engine-notice.js'
import {useEngineNotices} from '../shell/notice-context.js'
import {makeDraftStorage} from './draft-storage.js'
import {useSessionCaptures} from './session-captures.js'
import {makeToolViewCtx} from './tool-view-ctx.js'
import type {ComposerInputHandle} from './composer-input-adapter.js'
import {PaneComposer} from './pane-composer.js'
import {checkSend, type SendVerdict} from './send-checks.js'
import {usePaneMessaging} from './use-pane-messaging.js'

const GRAB_PREVIEW_MAX_W = 280

Expand All @@ -73,21 +71,6 @@ const ERROR = 'flex gap-2 items-center text-pw-danger text-[0.75rem] anim-msg'
const RETRY =
'py-1.5 px-2.5 min-h-8 rounded-[0.4375rem] border border-pw-danger-line bg-transparent text-pw-danger cursor-pointer font-semibold text-[0.75rem] leading-none font-pw shrink-0 trans-bg hover:bg-pw-danger-14'

type SendRejection = {rejected: true; message: string | null; tone: 'info' | 'warn'}

function sendRejection(verdict: Extract<SendVerdict, {ok: false}>): SendRejection {
return {rejected: true, message: verdict.message, tone: verdict.tone}
}

function isSendRejection(failure: unknown): failure is SendRejection {
return typeof failure === 'object' && failure !== null && 'rejected' in failure && failure.rejected === true
}

function failureMessage(failure: unknown): string {
if (failure instanceof Error && failure.message.length > 0) return failure.message
return 'The message could not be sent.'
}

function resetSlideOnSelf(reset: () => void) {
return (event: AnimationEvent) => {
if (event.target === event.currentTarget) reset()
Expand Down Expand Up @@ -138,6 +121,7 @@ export function ChatPane(props: {sessionId: string}): JSX.Element {
const appData = useAppData()
const announce = useAnnounce()
const connected = useConnected()
const {reachability, notices} = useEngineNotices()
const instances = useInstances()
const pane = usePane()
const sessionId = untrack(() => props.sessionId)
Expand Down Expand Up @@ -175,18 +159,23 @@ export function ChatPane(props: {sessionId: string}): JSX.Element {
{},
)

const uiReply = useMutation(() => ({
mutationFn: (input: {toolCallId: string; value: UiAnswerValue}) =>
rpc.chat.uiReply({sessionId, toolCallId: input.toolCallId, value: input.value}),
onError: () => notify('That question is no longer waiting for an answer.'),
}))
const messaging = usePaneMessaging({
rpc,
sessionId,
chat,
appData,
reachability,
notices,
grabStore: pane.grabStore,
refetchMarkers: () => markers.refetch(),
})

const toolCtx = makeToolViewCtx({
rpc,
harnessId: () => (meta.isPending ? '' : (meta.data?.harness.id ?? '')),
catalog,
sendMessage: (text) => void chat.sendMessage(text),
addResult: (toolCallId, value) => uiReply.mutate({toolCallId, value}),
addResult: (toolCallId, value) => messaging.uiReply.mutate({toolCallId, value}),
durationFor: (toolCallId) => durations()[toolCallId],
captureFor: captures.lookup,
})
Expand Down Expand Up @@ -223,20 +212,7 @@ export function ChatPane(props: {sessionId: string}): JSX.Element {
return now
}, false)

const visibleError = () => {
const error = chat.error()
return error && error.message !== 'stopped' ? error : undefined
}

const compact = useMutation(() => ({
mutationFn: () => rpc.sessions.compact({sessionId}),
onError: () => notify('Compaction failed. The session may be busy. Try again in a moment.'),
onSettled: () => {
appData.invalidateSessions()
void markers.refetch()
},
}))
const compacting = () => compact.isPending
const compacting = messaging.compacting

const triggerSources = useComposerTriggerSources(sessionId)
const focusInput = () => requestAnimationFrame(() => inputHandle()?.focus())
Expand Down Expand Up @@ -279,23 +255,6 @@ export function ChatPane(props: {sessionId: string}): JSX.Element {
const dividersInRange = (start: number, end: number): MarkerRow[] =>
(markers.data ?? []).filter((row) => row.afterTurn >= start && row.afterTurn <= end)

const onSend = async (content: string | MultimodalContent) => {
const verdict = checkSend(content, {
busy: compacting(),
connected: chat.connectionStatus() === 'connected',
})
if (!verdict.ok) throw sendRejection(verdict)
await chat.sendMessage(content)
pane.grabStore.clear()
}
const onSendError = (failure: unknown) => {
if (isSendRejection(failure)) {
if (failure.message) notify(failure.message, {tone: failure.tone === 'warn' ? 'warn' : 'info'})
return
}
notify(failureMessage(failure), {tone: 'danger'})
}

const renderDivider = (row: MarkerRow): JSX.Element => <Divider kind={row.kind} />
const renderTurnPrefix = (turn: Turn): JSX.Element => (
<For each={dividersInRange(turn.start, turn.end)}>{renderDivider}</For>
Expand All @@ -313,8 +272,8 @@ export function ChatPane(props: {sessionId: string}): JSX.Element {
<ToolProvider value={toolCtx}>
<ComposerHandlersProvider
value={{
onSend,
onSendError,
onSend: messaging.onSend,
onSendError: messaging.onSendError,
onRefresh: () => chat.refresh(),
onCancel: () => chat.interruptAndFlush(),
}}
Expand Down Expand Up @@ -355,7 +314,7 @@ export function ChatPane(props: {sessionId: string}): JSX.Element {
<Show when={nowTitleText()}>
{(title) => <NowLine title={title()} onStop={() => chat.stop()} />}
</Show>
<Show when={visibleError()}>
<Show when={messaging.visibleError()}>
{(error) => (
<div class={ERROR} role="alert">
<span class="flex-1">{error().message}</span>
Expand All @@ -371,8 +330,6 @@ export function ChatPane(props: {sessionId: string}): JSX.Element {
<Thread.Composer>
<ExtensionSurface name="status" instances={instances} />
<ExtensionSurface name="footer" instances={instances} />
<NoticeToaster />
<EngineStaleNotice />
<For each={pane.grabStore.grabs()}>
{(grab) => (
<GrabReference
Expand Down Expand Up @@ -402,7 +359,7 @@ export function ChatPane(props: {sessionId: string}): JSX.Element {
<ComposerActions
sessionId={sessionId}
compacting={compacting()}
onCompact={() => compact.mutate()}
onCompact={() => messaging.compact.mutate()}
onNewSession={() => pane.newSession()}
onStageGrab={stageGrab}
/>
Expand Down
59 changes: 23 additions & 36 deletions apps/conciv/src/pane/pane-composer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,10 @@ import Clock from 'lucide-solid/icons/clock'
import Paperclip from 'lucide-solid/icons/paperclip'
import RefreshCw from 'lucide-solid/icons/refresh-cw'
import Square from 'lucide-solid/icons/square'
import {
ComposerPrimitive,
QueueItem,
AttachmentUI,
useComposer,
useComposerContext,
useComposerHandlers,
type AttachmentAdapter,
} from '@conciv/ui-kit-chat'
import {Swap, TooltipIconButtonSlot} from '@conciv/ui-kit-system'
import {ComposerPrimitive, QueueItem, AttachmentUI, useComposer, type AttachmentAdapter} from '@conciv/ui-kit-chat'
import {TooltipIconButtonSlot} from '@conciv/ui-kit-system'
import type {WebStorage} from '@conciv/storage-history'
import {useEngineReachability} from '../app/reachability.js'
import {
ComposerInputAdapter,
type ComposerInputHandle,
Expand Down Expand Up @@ -49,34 +42,28 @@ const QUEUE_ROW =
const QUEUE_ACTION =
'shrink-0 px-2 py-1 rounded-[var(--chat-radius-sm)] bg-transparent [border:none] cursor-pointer font-medium text-[length:var(--chat-text-md)] leading-[1.45] [transition:background-color_120ms_var(--chat-ease),color_120ms_var(--chat-ease),transform_100ms_var(--chat-ease)] hover:[background:var(--chat-fill-strong)] [&:active]:scale-[0.96]'

function SendOrStopButton(): JSX.Element {
const ENGINE_UNREACHABLE_LABEL = 'conciv lost connection to the engine'

function ComposerSendControl(): JSX.Element {
const composer = useComposer()
const context = useComposerContext()
const handlers = useComposerHandlers()
const stopping = () => composer.canCancel()
const cancel = () => (handlers.onCancel ? handlers.onCancel() : composer.cancel())
const sendDisabled = () => context.sendingAttachments() || (!composer.canSend() && context.attachments().length === 0)
const reachability = useEngineReachability()
return (
<button
type={stopping() ? 'button' : 'submit'}
class={stopping() ? CANCEL : SEND}
aria-label={stopping() ? 'Stop generating' : 'Send message'}
disabled={!stopping() && sendDisabled()}
onClick={(event) => {
if (!stopping()) return
event.preventDefault()
cancel()
}}
>
<Swap.Root swap={stopping()}>
<Swap.Indicator type="on">
<Square size={14} fill="currentColor" aria-hidden="true" />
</Swap.Indicator>
<Swap.Indicator type="off">
<Show
when={composer.canCancel()}
fallback={
<ComposerPrimitive.Send
class={SEND}
disabled={!reachability.online()}
aria-label={reachability.online() ? 'Send message' : ENGINE_UNREACHABLE_LABEL}
>
<ArrowUp size={18} aria-hidden="true" />
</Swap.Indicator>
</Swap.Root>
</button>
</ComposerPrimitive.Send>
}
>
<ComposerPrimitive.Cancel class={CANCEL} aria-label="Stop generating">
<Square size={14} fill="currentColor" aria-hidden="true" />
</ComposerPrimitive.Cancel>
</Show>
)
}

Expand All @@ -90,7 +77,7 @@ function TrailingControls(): JSX.Element {
</ComposerPrimitive.Refresh>
)}
</TooltipIconButtonSlot>
<SendOrStopButton />
<ComposerSendControl />
</>
)
}
Expand Down
Loading
Loading