diff --git a/frontend/src/api/types.ts b/frontend/src/api/types.ts index 47d45217..ba32558b 100644 --- a/frontend/src/api/types.ts +++ b/frontend/src/api/types.ts @@ -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' -} diff --git a/frontend/src/components/ssh/SSHHostKeyDialog.tsx b/frontend/src/components/ssh/SSHHostKeyDialog.tsx index 209e05ff..851ad9f4 100644 --- a/frontend/src/components/ssh/SSHHostKeyDialog.tsx +++ b/frontend/src/components/ssh/SSHHostKeyDialog.tsx @@ -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' diff --git a/frontend/src/contexts/EventContext.test.tsx b/frontend/src/contexts/EventContext.test.tsx index 5206ab2f..094b6de9 100644 --- a/frontend/src/contexts/EventContext.test.tsx +++ b/frontend/src/contexts/EventContext.test.tsx @@ -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) => { @@ -192,6 +193,7 @@ function Harness() {
{location.pathname}
{location.search}
{location.key}
+
{sshHostKey.request?.host ?? 'none'}
@@ -941,6 +943,36 @@ describe('EventProvider permissions and forms', () => { }) }) + it('exposes an SSH host key request received via the global monitor onEvent', async () => { + render(, { 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' }]) diff --git a/frontend/src/contexts/EventContext.tsx b/frontend/src/contexts/EventContext.tsx index 5a3dda5c..721fa3d3 100644 --- a/frontend/src/contexts/EventContext.tsx +++ b/frontend/src/contexts/EventContext.tsx @@ -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 type PermissionsBySession = Record type FormsBySession = Record type SSEHealthState = Pick -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 diff --git a/frontend/src/hooks/useSSE.test.tsx b/frontend/src/hooks/useSSE.test.tsx index 5454cd58..1ace0ef4 100644 --- a/frontend/src/hooks/useSSE.test.tsx +++ b/frontend/src/hooks/useSSE.test.tsx @@ -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) diff --git a/frontend/src/hooks/useSSE.ts b/frontend/src/hooks/useSSE.ts index ce5f2b92..7513adb2 100644 --- a/frontend/src/hooks/useSSE.ts +++ b/frontend/src/hooks/useSSE.ts @@ -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, }) diff --git a/frontend/src/hooks/useSessionTranscript.test.tsx b/frontend/src/hooks/useSessionTranscript.test.tsx index e8d7e63d..e95ae376 100644 --- a/frontend/src/hooks/useSessionTranscript.test.tsx +++ b/frontend/src/hooks/useSessionTranscript.test.tsx @@ -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() { diff --git a/frontend/src/hooks/useSessionTranscript.ts b/frontend/src/hooks/useSessionTranscript.ts index 18873d39..9430c092 100644 --- a/frontend/src/hooks/useSessionTranscript.ts +++ b/frontend/src/hooks/useSessionTranscript.ts @@ -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) diff --git a/frontend/src/lib/opencode-event-stream/openCodeEventStream.ts b/frontend/src/lib/opencode-event-stream/openCodeEventStream.ts index 3b92b99b..d8cce348 100644 --- a/frontend/src/lib/opencode-event-stream/openCodeEventStream.ts +++ b/frontend/src/lib/opencode-event-stream/openCodeEventStream.ts @@ -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 { + 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() diff --git a/frontend/src/lib/opencode-event-stream/types.ts b/frontend/src/lib/opencode-event-stream/types.ts index 80274823..0eb3fa61 100644 --- a/frontend/src/lib/opencode-event-stream/types.ts +++ b/frontend/src/lib/opencode-event-stream/types.ts @@ -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 { diff --git a/frontend/src/lib/session-projection/applySessionEvent.test.ts b/frontend/src/lib/session-projection/applySessionEvent.test.ts index f2e28260..c6cda997 100644 --- a/frontend/src/lib/session-projection/applySessionEvent.test.ts +++ b/frontend/src/lib/session-projection/applySessionEvent.test.ts @@ -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) }) diff --git a/shared/src/schemas/index.ts b/shared/src/schemas/index.ts index 2935c783..d70baf9e 100644 --- a/shared/src/schemas/index.ts +++ b/shared/src/schemas/index.ts @@ -4,7 +4,6 @@ export * from './repo' export * from './git' export * from './files' export * from './filesystem' -export * from './opencode' export * from './auth' export * from './sse' export * from './notifications' diff --git a/shared/src/schemas/opencode.ts b/shared/src/schemas/opencode.ts deleted file mode 100644 index 35b96782..00000000 --- a/shared/src/schemas/opencode.ts +++ /dev/null @@ -1,47 +0,0 @@ -import { z } from 'zod' - -export const FileDiffSchema = z.object({ - file: z.string(), - before: z.string(), - after: z.string(), - additions: z.number(), - deletions: z.number(), -}) - -export const SessionSchema = z.object({ - id: z.string(), - projectID: z.string(), - directory: z.string(), - parentID: z.string().optional(), - summary: z.object({ - diffs: FileDiffSchema.array(), - }).optional(), - share: z.object({ - url: z.string(), - }).optional(), - title: z.string(), - version: z.string(), - time: z.object({ - created: z.number(), - updated: z.number(), - compacting: z.number().optional(), - }), - revert: z.object({ - messageID: z.string(), - partID: z.string().optional(), - snapshot: z.string().optional(), - diff: z.string().optional(), - }).optional(), -}) - -export const MessageSchema = z.object({ - id: z.string(), - sessionID: z.string(), - role: z.enum(['user', 'assistant']), - time: z.object({ - created: z.number(), - completed: z.number().optional(), - }), -}) - -export type FileDiff = z.infer \ No newline at end of file diff --git a/shared/src/schemas/sse.ts b/shared/src/schemas/sse.ts index 776c9f8c..ca2653db 100644 --- a/shared/src/schemas/sse.ts +++ b/shared/src/schemas/sse.ts @@ -1,5 +1,6 @@ import { z } from "zod"; import type { V2Event } from "../opencode"; +import type { SSHHostKeyRequest } from "./ssh"; export const SSESubscribeSchema = z.object({ clientId: z.string().min(1), @@ -16,8 +17,18 @@ export const SSEVisibilitySchema = z.object({ export type SSESubscribeRequest = z.infer; export type SSEVisibilityRequest = z.infer; +export interface SSHHostKeyRequestEvent { + type: "ssh.host-key-request"; + properties: SSHHostKeyRequest; +} + export interface SSEEventEnvelope { directory?: string | null; serverId?: string; - payload: V2Event; + payload: V2Event | SSHHostKeyRequestEvent; } + +export type OpenCodeStreamEvent = (V2Event | SSHHostKeyRequestEvent) & { + directory?: string; + serverId?: string; +}; diff --git a/shared/src/types/index.ts b/shared/src/types/index.ts index 3a4a07df..83498221 100644 --- a/shared/src/types/index.ts +++ b/shared/src/types/index.ts @@ -48,10 +48,6 @@ import { PatchOperationSchema, FilePatchRequestSchema, } from '../schemas/files' -import { - SessionSchema, - MessageSchema, -} from '../schemas/opencode' import { DirectoryEntrySchema, BrowseDirectoryResponseSchema, @@ -116,9 +112,6 @@ export type FileRangeRequest = z.infer export type PatchOperation = z.infer export type FilePatchRequest = z.infer -export type Session = z.infer -export type Message = z.infer - export type DirectoryEntry = z.infer export type BrowseDirectoryResponse = z.infer export type BrowseDirectoryRequest = z.infer