mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 20:34:18 +01:00
section 12: Phase 12: One shared flattened stream event type; delete the
This commit is contained in:
1 parent
0b2303a870
commit
717536c5a6
15 files changed
+122
-125
No files matched your search
@@ -36,15 +36,3 @@ export interface ImageAttachment {
|
||||
mime: string
|
||||
dataUrl: string
|
||||
}
|
||||
|
||||
export interface SSHHostKeyRequest {
|
||||
id: string
|
||||
requestId: string
|
||||
host: string
|
||||
ip?: string
|
||||
keyType: string
|
||||
fingerprint: string
|
||||
isKeyChanged?: boolean
|
||||
timestamp: number
|
||||
action: 'verify'
|
||||
}
|
||||
@@ -12,7 +12,7 @@ import { Alert, AlertDescription } from '@/components/ui/alert'
|
||||
import { CopyButton } from '@/components/ui/copy-button'
|
||||
import { Shield, ShieldAlert } from 'lucide-react'
|
||||
import { cn } from '@/lib/utils'
|
||||
import type { SSHHostKeyRequest } from '@/api/types'
|
||||
import type { SSHHostKeyRequest } from '@opencode-manager/shared/schemas'
|
||||
import { showToast } from '@/lib/toast'
|
||||
|
||||
type SSHHostKeyResponse = 'accept' | 'reject'
|
||||
|
||||
@@ -164,6 +164,7 @@ const childSessionForm: FormInfo = {
|
||||
function Harness() {
|
||||
const { current, pendingCount, syncForSession, navigateToCurrent, cancel, reply, getForSession } = useForms()
|
||||
const permissions = usePermissions()
|
||||
const { sshHostKey } = useEventContext()
|
||||
const location = useLocation()
|
||||
const [rejection, setRejection] = useState('none')
|
||||
const recordRejection = (action: Promise<void>) => {
|
||||
@@ -192,6 +193,7 @@ function Harness() {
|
||||
<div data-testid="path">{location.pathname}</div>
|
||||
<div data-testid="search">{location.search}</div>
|
||||
<div data-testid="location-key">{location.key}</div>
|
||||
<div data-testid="ssh-host">{sshHostKey.request?.host ?? 'none'}</div>
|
||||
<button onClick={() => syncForSession('/repo', 'session-1')}>Sync</button>
|
||||
<button onClick={() => permissions.syncForSession('/repo', 'session-1')}>Sync Permissions</button>
|
||||
<button onClick={navigateToCurrent}>Navigate</button>
|
||||
@@ -941,6 +943,36 @@ describe('EventProvider permissions and forms', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it('exposes an SSH host key request received via the global monitor onEvent', async () => {
|
||||
render(<Harness />, { wrapper: createWrapper() })
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1]
|
||||
const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void
|
||||
|
||||
act(() => {
|
||||
onEvent({
|
||||
type: 'ssh.host-key-request',
|
||||
properties: {
|
||||
id: 'host-key-1',
|
||||
host: 'example.com:22',
|
||||
ip: '203.0.113.10',
|
||||
keyType: 'ssh-ed25519',
|
||||
fingerprint: 'SHA256:abc',
|
||||
timestamp: Date.now(),
|
||||
isKeyChanged: false,
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('ssh-host')).toHaveTextContent('example.com:22')
|
||||
})
|
||||
})
|
||||
|
||||
it('adds a pending permission received via the global monitor onEvent', async () => {
|
||||
mocks.listRepos.mockResolvedValue([{ id: 123, fullPath: '/repo' }])
|
||||
|
||||
|
||||
@@ -14,13 +14,19 @@ import {
|
||||
} from '@/api/opencode'
|
||||
import { listRepos } from '@/api/repos'
|
||||
import { FetchError } from '@opencode-manager/shared'
|
||||
import { buildServerDirectoryKey, LOCAL_OPENCODE_SERVER_ID, parseServerDirectoryKey } from '@opencode-manager/shared/schemas'
|
||||
import {
|
||||
buildServerDirectoryKey,
|
||||
LOCAL_OPENCODE_SERVER_ID,
|
||||
parseServerDirectoryKey,
|
||||
type OpenCodeStreamEvent,
|
||||
type SSHHostKeyRequest,
|
||||
} from '@opencode-manager/shared/schemas'
|
||||
import { isLocalOpenCodeServer } from '@/contexts/OpenCodeServerContext'
|
||||
import { useAuth } from '@/hooks/useAuth'
|
||||
import { useOpenCodeServers } from '@/hooks/useOpenCodeServers'
|
||||
import { remoteProjectsQueryOptions } from '@/hooks/useRemoteProjects'
|
||||
import type { FormAnswer, FormInfo, PermissionRequest, V2Event } from '@opencode-manager/shared/opencode'
|
||||
import type { PermissionResponse, SSHHostKeyRequest, Repo } from '@/api/types'
|
||||
import type { FormAnswer, FormInfo, PermissionRequest } from '@opencode-manager/shared/opencode'
|
||||
import type { PermissionResponse, Repo } from '@/api/types'
|
||||
import { showToast } from '@/lib/toast'
|
||||
import { openCodeEventStream, type EventStreamHealthState } from '@/lib/opencode-event-stream'
|
||||
import { addToSessionKeyedState, removeFromSessionKeyedState } from '@/lib/sessionKeyedState'
|
||||
@@ -53,9 +59,6 @@ type PendingForm = ServerScoped<FormInfo>
|
||||
type PermissionsBySession = Record<string, PendingPermission[]>
|
||||
type FormsBySession = Record<string, PendingForm[]>
|
||||
type SSEHealthState = Pick<EventStreamHealthState, 'isConnected' | 'isHealthy' | 'isStalled'>
|
||||
type StreamEvent =
|
||||
| (V2Event & { directory?: string; serverId?: string })
|
||||
| { type: 'ssh.host-key-request'; properties: SSHHostKeyRequest }
|
||||
|
||||
type SessionScopedItem = { id: string; sessionID: string }
|
||||
|
||||
@@ -1046,11 +1049,8 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
|
||||
useEffect(() => {
|
||||
if (!isAuthenticated) return
|
||||
|
||||
const handleSSEMessage = (data: unknown) => {
|
||||
if (!data || typeof data !== 'object' || !('type' in data)) return
|
||||
|
||||
const event = data as StreamEvent
|
||||
const serverId = (event as { serverId?: string }).serverId ?? LOCAL_OPENCODE_SERVER_ID
|
||||
const handleSSEMessage = (event: OpenCodeStreamEvent) => {
|
||||
const serverId = event.serverId ?? LOCAL_OPENCODE_SERVER_ID
|
||||
|
||||
const goalEvent = { type: event.type, data: 'data' in event ? event.data : null }
|
||||
if (applySessionGoalEvent(queryClient, goalEvent, serverId)) return
|
||||
|
||||
@@ -51,7 +51,8 @@ class MockEventSource {
|
||||
close() {}
|
||||
|
||||
emit(type: string, data: unknown) {
|
||||
const event = { data: JSON.stringify(data) } as MessageEvent
|
||||
const message = type === 'message' ? { payload: data } : data
|
||||
const event = { data: JSON.stringify(message) } as MessageEvent
|
||||
this.listeners.get(type)?.forEach((listener) => listener(event))
|
||||
if (type === 'message' && this.onmessage) {
|
||||
this.onmessage(event)
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
import { useEffect, useRef, useState, useCallback, useMemo } from 'react'
|
||||
import { useQueryClient } from '@tanstack/react-query'
|
||||
import { buildServerDirectoryKey, LOCAL_OPENCODE_SERVER_ID } from '@opencode-manager/shared/schemas'
|
||||
import type { SessionInfo, V2Event } from '@opencode-manager/shared/opencode'
|
||||
import {
|
||||
buildServerDirectoryKey,
|
||||
LOCAL_OPENCODE_SERVER_ID,
|
||||
type OpenCodeStreamEvent,
|
||||
} from '@opencode-manager/shared/schemas'
|
||||
import type { SessionInfo } from '@opencode-manager/shared/opencode'
|
||||
import { invalidateSessionListCaches, invalidateShellCaches, shellsQueryKey } from '@/lib/queryInvalidation'
|
||||
import {
|
||||
applyShellExit,
|
||||
@@ -18,9 +22,7 @@ import type { EventStreamSubscription } from '@/lib/opencode-event-stream'
|
||||
import { serverScopedKey } from '@/lib/serverScope'
|
||||
import { useOpenCodeServerId } from '@/contexts/OpenCodeServerContext'
|
||||
|
||||
type V2StreamEvent = V2Event & { directory?: string; serverId?: string }
|
||||
|
||||
const getEventDirectory = (event: V2StreamEvent): string | undefined => {
|
||||
const getEventDirectory = (event: OpenCodeStreamEvent): string | undefined => {
|
||||
return typeof event.directory === 'string' ? event.directory : undefined
|
||||
}
|
||||
|
||||
@@ -73,7 +75,7 @@ export const useSSE = (directory?: string | string[], currentSessionId?: string)
|
||||
[directorySet, primaryDirectory],
|
||||
)
|
||||
|
||||
const handleSSEEvent = useCallback((event: V2StreamEvent) => {
|
||||
const handleSSEEvent = useCallback((event: OpenCodeStreamEvent) => {
|
||||
if ((event.serverId ?? LOCAL_OPENCODE_SERVER_ID) !== serverId) return
|
||||
const eventDirectory = getEventDirectory(event)
|
||||
const cacheDirectory = resolveCacheDirectory(eventDirectory)
|
||||
@@ -193,12 +195,6 @@ export const useSSE = (directory?: string | string[], currentSessionId?: string)
|
||||
return
|
||||
}
|
||||
|
||||
const handleMessage = (data: unknown) => {
|
||||
if (data && typeof data === 'object' && 'type' in data) {
|
||||
handleSSEEvent(data as V2StreamEvent)
|
||||
}
|
||||
}
|
||||
|
||||
const handleStatusChange = (connected: boolean) => {
|
||||
if (!mountedRef.current) return
|
||||
setIsConnected(connected)
|
||||
@@ -224,7 +220,7 @@ export const useSSE = (directory?: string | string[], currentSessionId?: string)
|
||||
|
||||
const subscription = openCodeEventStream.subscribeGlobalMonitor({
|
||||
directories: directoriesList.map((entry) => buildServerDirectoryKey(serverId, entry)),
|
||||
onEvent: handleMessage,
|
||||
onEvent: handleSSEEvent,
|
||||
onStatusChange: handleStatusChange,
|
||||
onResync: handleResync,
|
||||
})
|
||||
|
||||
@@ -71,7 +71,13 @@ interface TestTransport {
|
||||
}
|
||||
|
||||
function testTransport(): TestTransport {
|
||||
return mocks.transport as TestTransport
|
||||
const transport = mocks.transport as TestTransport
|
||||
return {
|
||||
connected: () => transport.connected(),
|
||||
fail: () => transport.fail(),
|
||||
message: (event) => transport.message({ payload: event }),
|
||||
resync: (payload) => transport.resync(payload),
|
||||
}
|
||||
}
|
||||
|
||||
function deferred<Value>() {
|
||||
|
||||
@@ -2,7 +2,11 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { FetchError } from '@opencode-manager/shared'
|
||||
import { sessionIDFromEvent, type V2Event } from '@opencode-manager/shared/opencode'
|
||||
import { buildServerDirectoryKey, LOCAL_OPENCODE_SERVER_ID } from '@opencode-manager/shared/schemas'
|
||||
import {
|
||||
buildServerDirectoryKey,
|
||||
LOCAL_OPENCODE_SERVER_ID,
|
||||
type OpenCodeStreamEvent,
|
||||
} from '@opencode-manager/shared/schemas'
|
||||
import { listSessionMessages, readSessionSnapshot } from '@/api/opencode'
|
||||
import { openCodeEventStream } from '@/lib/opencode-event-stream'
|
||||
import { sessionTranscriptQueryKey } from '@/lib/queryInvalidation'
|
||||
@@ -150,9 +154,9 @@ export function useSessionTranscript(sessionID: string, directory: string) {
|
||||
|
||||
const subscription = openCodeEventStream.subscribeGlobalMonitor({
|
||||
directories: [buildServerDirectoryKey(serverId, directory)],
|
||||
onEvent: (data) => {
|
||||
const event = data as V2Event & { serverId?: string }
|
||||
onEvent: (event: OpenCodeStreamEvent) => {
|
||||
if ((event.serverId ?? LOCAL_OPENCODE_SERVER_ID) !== serverId) return
|
||||
if (event.type === 'ssh.host-key-request') return
|
||||
if (sessionIDFromEvent(event) !== sessionID) return
|
||||
newestReadRef.current?.buffered.push(event)
|
||||
queuedEventsRef.current.push(event)
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
import { DEFAULTS } from '@opencode-manager/shared/config'
|
||||
import { LOCAL_OPENCODE_SERVER_ID, type SSEEventEnvelope } from '@opencode-manager/shared/schemas'
|
||||
import {
|
||||
LOCAL_OPENCODE_SERVER_ID,
|
||||
type OpenCodeStreamEvent,
|
||||
type SSHHostKeyRequestEvent,
|
||||
} from '@opencode-manager/shared/schemas'
|
||||
import type { V2Event } from '@opencode-manager/shared/opencode'
|
||||
import { createBrowserEventStreamTransport } from './browserTransport'
|
||||
import type {
|
||||
EventStreamHealthState,
|
||||
@@ -268,7 +273,8 @@ export class OpenCodeEventStream {
|
||||
private handleMessage(data: string): void {
|
||||
try {
|
||||
this.markActivity()
|
||||
this.broadcast(flattenEventEnvelope(JSON.parse(data)))
|
||||
const event = flattenEventEnvelope(JSON.parse(data))
|
||||
if (event) this.broadcast(event)
|
||||
} catch {
|
||||
this.markActivity()
|
||||
}
|
||||
@@ -427,10 +433,10 @@ export class OpenCodeEventStream {
|
||||
})
|
||||
}
|
||||
|
||||
private broadcast(data: unknown): void {
|
||||
private broadcast(event: OpenCodeStreamEvent): void {
|
||||
this.subscribers.forEach((subscriber) => {
|
||||
try {
|
||||
subscriber.onEvent(data)
|
||||
subscriber.onEvent(event)
|
||||
} catch {
|
||||
void 0
|
||||
}
|
||||
@@ -502,22 +508,22 @@ function parseResyncServerId(data?: string): string | undefined {
|
||||
}
|
||||
}
|
||||
|
||||
function flattenEventEnvelope(parsed: unknown): unknown {
|
||||
if (
|
||||
parsed !== null &&
|
||||
typeof parsed === 'object' &&
|
||||
'payload' in parsed &&
|
||||
(parsed as { payload: unknown }).payload !== null &&
|
||||
typeof (parsed as { payload: unknown }).payload === 'object'
|
||||
) {
|
||||
const { payload, directory, serverId } = parsed as SSEEventEnvelope
|
||||
return {
|
||||
...payload,
|
||||
...(typeof directory === 'string' ? { directory } : {}),
|
||||
...(typeof serverId === 'string' ? { serverId } : {}),
|
||||
}
|
||||
}
|
||||
return parsed
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return value !== null && typeof value === 'object'
|
||||
}
|
||||
|
||||
function isEventPayload(value: unknown): value is V2Event | SSHHostKeyRequestEvent {
|
||||
return isRecord(value) && typeof value.type === 'string'
|
||||
}
|
||||
|
||||
function flattenEventEnvelope(parsed: unknown): OpenCodeStreamEvent | null {
|
||||
if (!isRecord(parsed) || !isEventPayload(parsed.payload)) return null
|
||||
|
||||
const { payload, directory, serverId } = parsed
|
||||
const event: OpenCodeStreamEvent = { ...payload }
|
||||
if (typeof directory === 'string') event.directory = directory
|
||||
if (typeof serverId === 'string') event.serverId = serverId
|
||||
return event
|
||||
}
|
||||
|
||||
export const openCodeEventStream = new OpenCodeEventStream()
|
||||
@@ -1,4 +1,6 @@
|
||||
export type OpenCodeEventHandler = (data: unknown) => void
|
||||
import type { OpenCodeStreamEvent } from '@opencode-manager/shared/schemas'
|
||||
|
||||
export type OpenCodeEventHandler = (event: OpenCodeStreamEvent) => void
|
||||
export type EventStreamStatusHandler = (connected: boolean) => void
|
||||
|
||||
export interface EventStreamHealthState {
|
||||
|
||||
@@ -38,6 +38,12 @@ function applyAll(events: V2Event[]): SessionTranscript {
|
||||
return events.reduce(applySessionEvent, emptySessionTranscript)
|
||||
}
|
||||
|
||||
function eventAt(events: V2Event[], index: number): V2Event {
|
||||
const event = events[index]
|
||||
if (!event) throw new Error(`Missing event at index ${index}`)
|
||||
return event
|
||||
}
|
||||
|
||||
function assistantMessage(transcript: SessionTranscript): SessionMessageAssistant {
|
||||
const message = transcript.messages.at(-1)
|
||||
if (message?.type !== 'assistant') throw new Error('expected an assistant message')
|
||||
@@ -299,7 +305,7 @@ describe('applySessionEvent', () => {
|
||||
|
||||
it('ends only the running compaction and appends when none is running', () => {
|
||||
const failed = applyAll(failedCompactionSequence)
|
||||
const ended = applySessionEvent(failed, compactionSequence[2] as V2Event)
|
||||
const ended = applySessionEvent(failed, eventAt(compactionSequence, 2))
|
||||
|
||||
expect(ended.messages).toHaveLength(2)
|
||||
expect(ended.messages).toMatchObject([
|
||||
@@ -550,7 +556,7 @@ describe('applySessionEvent', () => {
|
||||
})
|
||||
|
||||
describe('sessionEventRequiresResync', () => {
|
||||
const executionEnded = executionSequence[1] as V2Event
|
||||
const executionEnded = eventAt(executionSequence, 1)
|
||||
|
||||
it('requires a resync when execution ends while a tool is still running', () => {
|
||||
const transcript = applyAll(promptSequence.slice(0, 15))
|
||||
@@ -573,7 +579,7 @@ describe('sessionEventRequiresResync', () => {
|
||||
it('does not require a resync for events other than execution end', () => {
|
||||
const transcript = applyAll(promptSequence.slice(0, 15))
|
||||
|
||||
expect(sessionEventRequiresResync(transcript, promptSequence[14] as V2Event)).toBe(false)
|
||||
expect(sessionEventRequiresResync(transcript, eventAt(promptSequence, 14))).toBe(false)
|
||||
})
|
||||
|
||||
it('requires a resync when assistant message content is updated', () => {
|
||||
@@ -641,14 +647,14 @@ describe('applySessionEvents', () => {
|
||||
|
||||
it('reports requiresResync for a flush that ends execution with an unsettled tool', () => {
|
||||
const running = applyAll(promptSequence.slice(0, 15))
|
||||
const batch = applySessionEvents(running, [executionSequence[1] as V2Event])
|
||||
const batch = applySessionEvents(running, [eventAt(executionSequence, 1)])
|
||||
|
||||
expect(batch.requiresResync).toBe(true)
|
||||
})
|
||||
|
||||
it('does not report requiresResync for a settled flush', () => {
|
||||
const settled = applyAll(promptSequence)
|
||||
const batch = applySessionEvents(settled, [executionSequence[1] as V2Event])
|
||||
const batch = applySessionEvents(settled, [eventAt(executionSequence, 1)])
|
||||
|
||||
expect(batch.requiresResync).toBe(false)
|
||||
})
|
||||
@@ -666,7 +672,7 @@ describe('applySessionEvents', () => {
|
||||
|
||||
it('returns the base transcript when no event changes it', () => {
|
||||
const base = applyAll(promptSequence)
|
||||
const batch = applySessionEvents(base, [promptSequence[13] as V2Event])
|
||||
const batch = applySessionEvents(base, [eventAt(promptSequence, 13)])
|
||||
|
||||
expect(batch.transcript).toBe(base)
|
||||
})
|
||||
|
||||
Reference in new issue
Block a user