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
6 changes: 3 additions & 3 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,11 @@ Figma-like infinite canvas for supervising live OpenCode agent session trees in
- PR #11 merged (project creation + canvas filtering)

## Active Objective
Phase 6: TBD
Phase 6: `GET /api/agent/tree` 감독용 조회 API + SSE 재연결/오류복구 마무리

### Candidates (Future Roadmap):
- Supervisor agent support (compact /api/tree for agent consumption)
- Project v2: manual session reassignment, colors/icons, filtering
- 추가 agent-facing compact API는 현재 Phase 6 acceptance 이후 재평가

## PM Role

Expand Down Expand Up @@ -60,5 +60,5 @@ Phase 6: TBD
- opencode SDK (@opencode-ai/sdk) -- upstream API surface

## Future Roadmap
- Supervisor agent support (compact /api/tree for agent consumption)
- Project v2: manual session reassignment, colors/icons, filtering
- 추가 compact API / agent-facing API는 Phase 6 종료 후 별도 판단
44 changes: 42 additions & 2 deletions src/client/canvas/AgentCanvas.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,8 @@ export function AgentCanvas() {
const onNodesChange = useAgentStore((s) => s.onNodesChange)
const pinNode = useAgentStore((s) => s.pinNode)
const addRelation = useAgentStore((s) => s.addRelation)
const sseStatus = useAgentStore((s) => s.sseStatus)
const setSseStatus = useAgentStore((s) => s.setSseStatus)
const hasFramedInitialView = useRef(false)
const [pendingConn, setPendingConn] = useState<{ source: string; target: string } | null>(null)
const [treeError, setTreeError] = useState<string | null>(null)
Expand Down Expand Up @@ -208,10 +210,22 @@ export function AgentCanvas() {
let es: EventSource | null = null
let cancelled = false
let retryTimeout: ReturnType<typeof setTimeout> | null = null
let retryMs = 1000
const MAX_RETRY_MS = 30_000
let hasConnectedOnce = false

function connect() {
if (cancelled) return
es = new EventSource('/api/events')
es.onopen = () => {
const shouldReloadTree = hasConnectedOnce
hasConnectedOnce = true
retryMs = 1000
setSseStatus('connected')
if (shouldReloadTree) {
reloadTree().catch(console.error)
}
Comment on lines +225 to +227
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Triggering reloadTree() immediately upon every SSE reconnection can lead to excessive network requests if the connection is unstable. Consider implementing a debounced reload or a check to see if the tree state has actually changed before performing a full fetch.

}
es.onmessage = (e) => {
try {
const event = JSON.parse(e.data)
Expand All @@ -222,10 +236,16 @@ export function AgentCanvas() {
} catch (err) { console.warn('[sse] failed to parse event:', err) }
}
es.onerror = () => {
console.warn('[sse] connection lost, reconnecting in 3s...')
es?.close()
es = null
if (!cancelled) retryTimeout = setTimeout(connect, 3000)
if (!cancelled) {
const delay = retryMs
retryMs = Math.min(retryMs * 2, MAX_RETRY_MS)
const status = delay >= MAX_RETRY_MS ? 'disconnected' : 'reconnecting'
setSseStatus(status)
console.warn(`[sse] connection lost, reconnecting in ${delay / 1000}s...`)
retryTimeout = setTimeout(connect, delay)
}
}
}

Expand Down Expand Up @@ -299,6 +319,26 @@ export function AgentCanvas() {
</button>
</div>
)}
{sseStatus !== 'connected' && (
<div style={{
position: 'absolute', top: treeError ? 60 : 16, left: '50%', transform: 'translateX(-50%)', zIndex: 20,
background: sseStatus === 'disconnected' ? '#1c1917' : '#1c1917',
border: `1px solid ${sseStatus === 'disconnected' ? '#ef4444' : '#f59e0b'}`,
color: sseStatus === 'disconnected' ? '#fca5a5' : '#fcd34d',
padding: '6px 14px', borderRadius: 8,
fontSize: 12, display: 'flex', alignItems: 'center', gap: 8,
whiteSpace: 'nowrap',
}}>
<span
style={{
width: 7, height: 7, borderRadius: '50%',
background: sseStatus === 'disconnected' ? '#ef4444' : '#f59e0b',
flexShrink: 0,
}}
/>
{sseStatus === 'disconnected' ? 'Disconnected from server' : 'Reconnecting…'}
</div>
)}
<div
style={{
position: 'absolute',
Expand Down
5 changes: 5 additions & 0 deletions src/client/store/agentStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ export const STATUS_COLORS: Record<NodeStatus, string> = {
export type ViewMode = 'recent' | 'all'
export type RelationType = 'fork' | 'linked' | 'detached'
export type AppView = 'home' | 'canvas'
export type SseStatus = 'connected' | 'reconnecting' | 'disconnected'
export type ActiveProjectKey = string | null

export type Project = {
Expand Down Expand Up @@ -542,6 +543,8 @@ type AgentStore = {
appView: AppView
activeProjectKey: string | null
pendingScrollToSessionId: string | null
sseStatus: SseStatus
setSseStatus: (status: SseStatus) => void
addRelation: (fromSessionId: string, toSessionId: string, relationType: string) => Promise<void>
removeRelation: (id: number) => Promise<void>
setSelectedSession: (id: string | null) => void
Expand Down Expand Up @@ -578,6 +581,8 @@ export const useAgentStore = create<AgentStore>((set, get) => ({
appView: 'home',
activeProjectKey: null,
pendingScrollToSessionId: null,
sseStatus: 'disconnected',
setSseStatus: (status) => set({ sseStatus: status }),

addRelation: async (fromSessionId, toSessionId, relationType) => {
const res = await fetch('/api/relation', {
Expand Down
2 changes: 2 additions & 0 deletions src/server/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { approvalRouter } from './routes/approval.js'
import { systemRouter } from './routes/system.js'
import { relationRouter } from './routes/relation.js'
import { projectRouter } from './routes/project.js'
import { agentRouter } from './routes/agent.js'
import { sseHandler, isOpencodeConnected } from './sse/broadcaster.js'

type AppOptions = {
Expand Down Expand Up @@ -42,6 +43,7 @@ export function createApp(options: AppOptions = {}) {
app.route('/', systemRouter)
app.route('/', relationRouter)
app.route('/', projectRouter)
app.route('/', agentRouter)

// Static file serving for production CLI mode — must come after all /api routes
if (options.staticDir) {
Expand Down
176 changes: 176 additions & 0 deletions src/server/routes/agent.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,176 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { Hono } from 'hono'

vi.mock('../opencode/index.js', () => ({
opencodeAdapter: {
listSessions: vi.fn(),
listStatuses: vi.fn(),
},
}))

vi.mock('../db/index.js', () => ({
getAllCanvasNodes: vi.fn(),
getAllProjects: vi.fn(),
getForkRelationMap: vi.fn(),
getAllSessionRelations: vi.fn(),
getAllTaskInvocations: vi.fn(),
findOrCreateProject: vi.fn(),
setCanvasNodeProject: vi.fn(),
}))

vi.mock('../sse/broadcaster.js', () => ({
getPendingPermissions: vi.fn(),
getPendingQuestions: vi.fn(),
}))

import { opencodeAdapter } from '../opencode/index.js'
import {
getAllCanvasNodes,
getAllProjects,
getForkRelationMap,
getAllSessionRelations,
getAllTaskInvocations,
findOrCreateProject,
} from '../db/index.js'
import { getPendingPermissions, getPendingQuestions } from '../sse/broadcaster.js'
import { agentRouter } from './agent.js'

const app = new Hono()
app.route('/', agentRouter)

const mockSessions = [
{ id: 'sess-1', title: 'First', parentID: null, directory: '/home/statpan/workspace/apps/agentree', time: { created: 1000, updated: 2000 } },
{ id: 'sess-2', title: 'Second', parentID: 'sess-1', directory: '/home/statpan/workspace/apps/agentree', time: { created: 1100, updated: 2100 } },
]

const mockProject = { id: 'proj-1', name: 'apps/agentree', directory_key: 'apps/agentree', user_created: 0, created_at: '2024-01-01' }

beforeEach(() => {
vi.clearAllMocks()
vi.mocked(opencodeAdapter.listSessions).mockResolvedValue(mockSessions)
vi.mocked(opencodeAdapter.listStatuses).mockResolvedValue({ 'sess-1': 'running', 'sess-2': 'idle' })
vi.mocked(getAllCanvasNodes).mockReturnValue([
{ session_id: 'sess-1', label: null, canvas_x: 0, canvas_y: 0, pinned: 0, detached: 0, project_id: 'proj-1', updated_at: '' },
{ session_id: 'sess-2', label: null, canvas_x: 0, canvas_y: 0, pinned: 0, detached: 0, project_id: 'proj-1', updated_at: '' },
])
vi.mocked(getAllProjects).mockReturnValue([mockProject])
vi.mocked(getForkRelationMap).mockReturnValue(new Map())
vi.mocked(getAllSessionRelations).mockReturnValue([])
vi.mocked(getAllTaskInvocations).mockReturnValue([])
vi.mocked(findOrCreateProject).mockReturnValue(mockProject)
vi.mocked(getPendingPermissions).mockReturnValue([])
vi.mocked(getPendingQuestions).mockReturnValue([])
})

describe('GET /api/agent/tree', () => {
it('returns all sessions with statuses when no projectId filter', async () => {
const res = await app.request('/api/agent/tree')
expect(res.status).toBe(200)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const body = await res.json() as any
expect(typeof body.ts).toBe('number')
expect(body.sessions).toHaveLength(2)
expect(body.sessions[0]).toMatchObject({ id: 'sess-1', status: 'running', ts: 2000, forkedFrom: null })
expect(body.sessions[1]).toMatchObject({ id: 'sess-2', status: 'idle', ts: 2100, forkedFrom: null })
})

it('includes relations, taskInvocations, pendingPermissions, pendingQuestions, projects', async () => {
const res = await app.request('/api/agent/tree')
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const body = await res.json() as any
expect(body).toHaveProperty('relations')
expect(body).toHaveProperty('taskInvocations')
expect(body).toHaveProperty('pendingPermissions')
expect(body).toHaveProperty('pendingQuestions')
expect(body).toHaveProperty('projects')
})

it('filters sessions by projectId query param', async () => {
// Make sess-2 belong to a different project
vi.mocked(getAllCanvasNodes).mockReturnValue([
{ session_id: 'sess-1', label: null, canvas_x: 0, canvas_y: 0, pinned: 0, detached: 0, project_id: 'proj-1', updated_at: '' },
{ session_id: 'sess-2', label: null, canvas_x: 0, canvas_y: 0, pinned: 0, detached: 0, project_id: 'proj-2', updated_at: '' },
])
const res = await app.request('/api/agent/tree?projectId=proj-1')
expect(res.status).toBe(200)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const body = await res.json() as any
expect(body.sessions).toHaveLength(1)
expect(body.sessions[0].id).toBe('sess-1')
})

it('exposes forkedFrom via fork relation map and omits fork overlays from relations', async () => {
vi.mocked(getForkRelationMap).mockReturnValue(new Map([['sess-2', 'sess-1']]))
vi.mocked(getAllSessionRelations).mockReturnValue([
{ id: 1, from_session_id: 'sess-1', to_session_id: 'sess-2', relation_type: 'linked', created_at: '' },
{ id: 2, from_session_id: 'sess-1', to_session_id: 'sess-2', relation_type: 'fork', created_at: '' },
])

const res = await app.request('/api/agent/tree')
expect(res.status).toBe(200)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const body = await res.json() as any
expect(body.sessions.find((session: { id: string }) => session.id === 'sess-2')?.forkedFrom).toBe('sess-1')
expect(body.relations).toHaveLength(1)
expect(body.relations[0].relation_type).toBe('linked')
})

it('returns 502 when listSessions fails', async () => {
vi.mocked(opencodeAdapter.listSessions).mockRejectedValue(new Error('opencode down'))
const res = await app.request('/api/agent/tree')
expect(res.status).toBe(502)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const body = await res.json() as any
expect(body.error).toMatch(/opencode down/)
})

it('exposes pending permissions and questions from broadcaster', async () => {
vi.mocked(getPendingPermissions).mockReturnValue([
{ requestId: 'req-1', sessionId: 'sess-1', message: 'Allow file write?', metadata: {} },
])
vi.mocked(getPendingQuestions).mockReturnValue([
{ requestId: 'q-1', sessionId: 'sess-1', message: 'Which branch?', metadata: {} },
])
const res = await app.request('/api/agent/tree')
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const body = await res.json() as any
expect(body.pendingPermissions).toHaveLength(1)
expect(body.pendingPermissions[0].requestId).toBe('req-1')
expect(body.pendingQuestions).toHaveLength(1)
expect(body.pendingQuestions[0].requestId).toBe('q-1')
})

it('overrides session status when a pending permission exists', async () => {
vi.mocked(getPendingPermissions).mockReturnValue([
{ requestId: 'req-1', sessionId: 'sess-1', message: 'Allow file write?', metadata: {} },
])

const res = await app.request('/api/agent/tree')
expect(res.status).toBe(200)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const body = await res.json() as any
expect(body.sessions.find((session: { id: string }) => session.id === 'sess-1')?.status).toBe('needs-permission')
})

it('filters pending items by projectId (only items for visible sessions)', async () => {
vi.mocked(getPendingPermissions).mockReturnValue([
{ requestId: 'req-1', sessionId: 'sess-1', message: 'Allow?', metadata: {} },
{ requestId: 'req-2', sessionId: 'other-sess', message: 'Other?', metadata: {} },
])
const res = await app.request('/api/agent/tree?projectId=proj-1')
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const body = await res.json() as any
// sess-1 is in proj-1, other-sess is not in sessions → filtered out
expect(body.pendingPermissions).toHaveLength(1)
expect(body.pendingPermissions[0].requestId).toBe('req-1')
})

it('falls back to idle status when listStatuses fails', async () => {
vi.mocked(opencodeAdapter.listStatuses).mockRejectedValue(new Error('status unavailable'))
const res = await app.request('/api/agent/tree')
expect(res.status).toBe(200)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const body = await res.json() as any
expect(body.sessions[0].status).toBe('idle')
})
})
Loading
Loading