From 7a46fa27c592881de494e2b35196d2697229dbff Mon Sep 17 00:00:00 2001 From: Chris Scott <99081550+chriswritescode-dev@users.noreply.github.com> Date: Tue, 21 Apr 2026 12:29:06 -0400 Subject: [PATCH] feat(workspace): switch to local workspace targeting with TUI prewarming --- backend/src/index.ts | 14 +- backend/src/routes/workspace-plugin.ts | 48 ------ .../src/services/opencode-single-server.ts | 18 ++- backend/src/services/proxy-ws.ts | 19 +-- backend/src/services/proxy.ts | 65 ++++---- backend/src/services/schedule-config.ts | 12 +- backend/src/services/schedules.ts | 35 +++-- backend/src/utils/proxy-timeout.ts | 6 +- backend/test/routes/workspace-plugin.test.ts | 114 +------------- backend/test/services/proxy-ws.test.ts | 12 +- backend/test/services/proxy.test.ts | 76 --------- backend/test/services/schedules.test.ts | 32 ++++ backend/test/utils/proxy-timeout.test.ts | 52 +++++++ docs/features/workspace-plugin.md | 128 ++++++---------- packages/workspace-plugin/README.md | 50 +++--- packages/workspace-plugin/package.json | 13 +- packages/workspace-plugin/src/index.ts | 76 +++++---- packages/workspace-plugin/src/tui.ts | 144 ++++++++++++++++++ packages/workspace-plugin/test/index.test.ts | 95 +++++++++--- 19 files changed, 530 insertions(+), 479 deletions(-) create mode 100644 backend/test/utils/proxy-timeout.test.ts create mode 100644 packages/workspace-plugin/src/tui.ts diff --git a/backend/src/index.ts b/backend/src/index.ts index b6e696ce..c9a262c5 100644 --- a/backend/src/index.ts +++ b/backend/src/index.ts @@ -51,7 +51,6 @@ import { createApiTokenRoutes } from './routes/api-tokens' import { createWorkspacePluginRoutes } from './routes/workspace-plugin' import { attachWorkspacePluginWs } from './services/proxy-ws' import type { Server } from 'node:http' -import { listRepos } from './db/queries' import { logger } from './utils/logger' import { @@ -295,19 +294,9 @@ app.post('/api/opencode/mcp/:name/auth/authenticate', requireAuth, async (c) => return proxyMcpAuthAuthenticate(serverName, directory) }) -const projectService: import('./services/proxy').ProxyProjectService = { - getBySlug: (slug: string) => { - const settings = new SettingsService(db).getSettings() - const repos = listRepos(db, settings.preferences.repoOrder) - const repo = repos.find((r) => r.id.toString() === slug) - if (!repo) return null - return { directory: repo.fullPath } - }, -} - app.all('/api/opencode/*', requireAuth, async (c) => { const request = c.req.raw - return proxyRequest(request, projectService) + return proxyRequest(request) }) const isProduction = ENV.SERVER.NODE_ENV === 'production' @@ -428,7 +417,6 @@ const verifyPluginBearerAuth = async (headers: Headers): Promise<{ userId: strin attachWorkspacePluginWs(server, { upstreamBaseUrl: OPENCODE_SERVER_URL, verifyAuth: verifyPluginBearerAuth, - projectService, pathPrefix: '/api/opencode', }) diff --git a/backend/src/routes/workspace-plugin.ts b/backend/src/routes/workspace-plugin.ts index 97d39154..616dbe68 100644 --- a/backend/src/routes/workspace-plugin.ts +++ b/backend/src/routes/workspace-plugin.ts @@ -4,7 +4,6 @@ import { listRepos } from '../db/queries' import { SettingsService } from '../services/settings' import { logger } from '../utils/logger' import type { Session } from '../auth' -import { proxyRequest, type ProxyProjectService } from '../services/proxy' type AppVariables = { session: Session['session'] @@ -24,17 +23,6 @@ const ALLOWED_WORKSPACE_PLUGIN_SCOPES = new Set(['*', 'workspace-plugin']) export function createWorkspacePluginRoutes(db: Database) { const app = new Hono<{ Variables: AppVariables }>() - const projectService: ProxyProjectService = { - getBySlug: (slug: string) => { - const settingsService = new SettingsService(db) - const settings = settingsService.getSettings() - const repos = listRepos(db, settings.preferences.repoOrder) - const repo = repos.find((r) => r.id.toString() === slug) - if (!repo) return null - return { directory: repo.fullPath } - }, - } - app.get('/projects', async (c) => { try { const session = c.get('session') @@ -72,41 +60,5 @@ export function createWorkspacePluginRoutes(db: Database) { } }) - app.all('/opencode/:slug/*', async (c) => { - const slug = c.req.param('slug') - const inbound = c.req.raw - const inboundUrl = new URL(inbound.url) - logger.info(`workspace-plugin proxy inbound: ${inbound.method} ${inboundUrl.pathname}${inboundUrl.search} slug=${slug}`) - - const session = c.get('session') - if (!session) { - logger.warn(`workspace-plugin proxy: unauthorized (no session) slug=${slug} path=${inboundUrl.pathname}`) - return c.json({ error: 'Unauthorized' }, 401) - } - - const tokenScope = c.get('tokenScope') - if (tokenScope !== undefined && !ALLOWED_WORKSPACE_PLUGIN_SCOPES.has(tokenScope)) { - logger.warn(`Token with scope '${tokenScope}' attempted to access workspace-plugin opencode proxy`) - return c.json({ error: 'Forbidden: insufficient token scope' }, 403) - } - - const rewritten = new URL(inbound.url) - const prefix = `/api/workspace-plugin/opencode/${slug}` - const rest = inboundUrl.pathname.slice(prefix.length) || '/' - rewritten.pathname = `/api/opencode${rest}` - - const forwardedHeaders = new Headers(inbound.headers) - forwardedHeaders.set('x-opencode-manager-project', slug) - const forwarded = new Request(rewritten.toString(), { - method: inbound.method, - headers: forwardedHeaders, - body: inbound.method === 'GET' || inbound.method === 'HEAD' ? undefined : inbound.body, - duplex: 'half', - }) - - logger.info(`workspace-plugin proxy forward: ${forwarded.method} ${rewritten.pathname}${rewritten.search} -> upstream opencode (slug=${slug})`) - return proxyRequest(forwarded, projectService) - }) - return app } diff --git a/backend/src/services/opencode-single-server.ts b/backend/src/services/opencode-single-server.ts index 2bcb5626..f45b1c2f 100644 --- a/backend/src/services/opencode-single-server.ts +++ b/backend/src/services/opencode-single-server.ts @@ -248,7 +248,13 @@ class OpenCodeServerManager { this.serverProcess = spawn( 'opencode', - ['serve', '--port', OPENCODE_SERVER_PORT.toString(), '--hostname', OPENCODE_SERVER_HOST], + [ + 'serve', + '--port', OPENCODE_SERVER_PORT.toString(), + '--hostname', OPENCODE_SERVER_HOST, + '--print-logs', + '--log-level', 'DEBUG', + ], { cwd: openCodeServerDirectory, detached: !isDevelopment, @@ -275,13 +281,21 @@ class OpenCodeServerManager { if (!isDevelopment && this.serverProcess.stderr) { this.serverProcess.stderr.on('data', (data) => { - stderrOutput += data.toString() + const chunk = data.toString() + process.stderr.write(chunk) + stderrOutput += chunk if (stderrOutput.length > MAX_STDERR_SIZE) { stderrOutput = stderrOutput.slice(-MAX_STDERR_SIZE) } }) } + if (!isDevelopment && this.serverProcess.stdout) { + this.serverProcess.stdout.on('data', (data) => { + process.stdout.write(data) + }) + } + this.serverProcess.on('exit', (code, signal) => { if (code !== null && code !== 0) { const fallback = `Server exited with code ${code}${stderrOutput ? `: ${stderrOutput.slice(-500)}` : ''}` diff --git a/backend/src/services/proxy-ws.ts b/backend/src/services/proxy-ws.ts index b50e6d94..07ae39d7 100644 --- a/backend/src/services/proxy-ws.ts +++ b/backend/src/services/proxy-ws.ts @@ -10,14 +10,9 @@ interface AuthResult { scope: string } -interface ProjectService { - getBySlug: (slug: string) => { directory: string } | null -} - export interface WebSocketProxyOptions { upstreamBaseUrl: string verifyAuth: (headers: Headers) => Promise - projectService?: ProjectService pathPrefix?: string } @@ -107,19 +102,7 @@ export function attachWorkspacePluginWs(server: Server, options: WebSocketProxyO } const remainingPath = url.pathname.slice(pathPrefix.length) || '/' - let targetUrl = `${options.upstreamBaseUrl}${remainingPath}${url.search}` - - const slugHeader = headers.get('x-opencode-manager-project') - if (slugHeader && options.projectService) { - const project = options.projectService.getBySlug(slugHeader) - if (!project) { - rejectUpgrade(socket, 404, 'Not Found') - return - } - const targetUrlObj = new URL(targetUrl) - targetUrlObj.searchParams.set('directory', project.directory) - targetUrl = targetUrlObj.toString() - } + const targetUrl = `${options.upstreamBaseUrl}${remainingPath}${url.search}` const upstreamWsUrl = (() => { const u = new URL(targetUrl) diff --git a/backend/src/services/proxy.ts b/backend/src/services/proxy.ts index d29401b0..4f766e94 100644 --- a/backend/src/services/proxy.ts +++ b/backend/src/services/proxy.ts @@ -288,35 +288,42 @@ export async function patchOpenCodeConfig(config: Record): Prom } } -export interface ProxyProjectService { - getBySlug: (slug: string) => { directory: string } | null -} +const HOP_BY_HOP_REQUEST_HEADERS = new Set([ + 'connection', + 'keep-alive', + 'proxy-authenticate', + 'proxy-authorization', + 'proxy-connection', + 'te', + 'trailer', + 'transfer-encoding', + 'upgrade', + 'host', + 'authorization', + 'accept-encoding', + 'x-opencode-directory', + 'x-opencode-workspace', +]) -const HOP_BY_HOP_REQUEST_HEADERS = new Set(['host', 'connection', 'authorization']) -const HOP_BY_HOP_RESPONSE_HEADERS = new Set(['connection', 'transfer-encoding', 'content-encoding', 'content-length']) +const HOP_BY_HOP_RESPONSE_HEADERS = new Set([ + 'connection', + 'keep-alive', + 'proxy-authenticate', + 'proxy-authorization', + 'proxy-connection', + 'te', + 'trailer', + 'transfer-encoding', + 'upgrade', + 'content-encoding', + 'content-length', +]) -export async function proxyRequest(request: Request, projectService?: ProxyProjectService) { +export async function proxyRequest(request: Request) { const url = new URL(request.url) - // Remove /api/opencode prefix from pathname before forwarding const cleanPathname = url.pathname.replace(/^\/api\/opencode/, '') - let targetUrl = `${OPENCODE_SERVER_URL}${cleanPathname}${url.search}` - - if (url.pathname.includes('/permissions/')) { - logger.info(`Proxying permission request: ${url.pathname}${url.search} -> ${targetUrl}`) - } - - // Handle project slug header translation - const slugHeader = request.headers.get('x-opencode-manager-project') - if (slugHeader && projectService) { - const project = projectService.getBySlug(slugHeader) - if (!project) { - return new Response('Unknown project', { status: 404 }) - } - const targetUrlObj = new URL(targetUrl) - targetUrlObj.searchParams.set('directory', project.directory) - targetUrl = targetUrlObj.toString() - } + const targetUrl = `${OPENCODE_SERVER_URL}${cleanPathname}${url.search}` try { const headers: Record = {} @@ -326,6 +333,8 @@ export async function proxyRequest(request: Request, projectService?: ProxyProje } }) + headers['accept-encoding'] = 'identity' + const fetchOptions: RequestInit & { duplex?: string } = { method: request.method, headers: withOpenCodeAuth(headers), @@ -333,17 +342,16 @@ export async function proxyRequest(request: Request, projectService?: ProxyProje } if (request.method !== 'GET' && request.method !== 'HEAD') { - // Buffer the request body before forwarding. Streaming with `duplex: 'half'` - // is unreliable across runtimes (Bun vs Node) and breaks when upstream - // middleware has already touched the body. Buffering is safe for typical - // OpenCode payloads (JSON commands, small uploads). const bodyBuffer = await request.arrayBuffer() if (bodyBuffer.byteLength > 0) { fetchOptions.body = bodyBuffer } } + logger.debug(`proxy fetch start: ${request.method} ${targetUrl}`) + const fetchStart = Date.now() const response = await fetch(targetUrl, fetchOptions) + logger.debug(`proxy fetch done: ${request.method} ${targetUrl} status=${response.status} ms=${Date.now() - fetchStart}`) const responseHeaders: Record = {} response.headers.forEach((value, key) => { @@ -352,7 +360,6 @@ export async function proxyRequest(request: Request, projectService?: ProxyProje } }) - // Stream the response body for SSE support return new Response(response.body, { status: response.status, statusText: response.statusText, diff --git a/backend/src/services/schedule-config.ts b/backend/src/services/schedule-config.ts index 74e58831..7bc6504e 100644 --- a/backend/src/services/schedule-config.ts +++ b/backend/src/services/schedule-config.ts @@ -35,11 +35,15 @@ function validateTimeZone(timezone: string): string { function getCronNextRunAt(cronExpression: string, timezone: string, currentDate: number): number { const cron = new Cron(cronExpression, { timezone }) - const next = cron.nextRun(new Date(currentDate)) - if (!next) { - throw new Error(`Cron expression "${cronExpression}" has no upcoming run`) + try { + const next = cron.nextRun(new Date(currentDate)) + if (!next) { + throw new Error(`Cron expression "${cronExpression}" has no upcoming run`) + } + return next.getTime() + } finally { + cron.stop() } - return next.getTime() } function normalizeCronConfig(cronExpression: string, timezone: string | null | undefined, currentDate: number) { diff --git a/backend/src/services/schedules.ts b/backend/src/services/schedules.ts index 0da81157..9649bf2d 100644 --- a/backend/src/services/schedules.ts +++ b/backend/src/services/schedules.ts @@ -1094,28 +1094,45 @@ function buildIntervalCronExpression(intervalMinutes: number): string | null { export class ScheduleRunner { private cronJobs = new Map() + private isStarted = false + private readonly onJobChange = (job: ScheduleJob | null, jobId: number): void => { + if (job) { + this.registerJob(job) + } else { + this.unregisterJob(jobId) + } + } constructor(private readonly scheduleService: ScheduleService) {} async start(): Promise { - this.scheduleService.setJobChangeHandler((job, jobId) => { - if (job) { - this.registerJob(job) - } else { - this.unregisterJob(jobId) - } - }) + if (this.isStarted) { + return + } - await this.scheduleService.recoverRunningRuns() - this.registerAllEnabledJobs() + this.isStarted = true + this.scheduleService.setJobChangeHandler(this.onJobChange) + + try { + await this.scheduleService.recoverRunningRuns() + this.registerAllEnabledJobs() + } catch (error) { + this.stop() + throw error + } } stop(): void { + if (!this.isStarted) { + return + } + this.scheduleService.setJobChangeHandler(null) for (const stoppable of this.cronJobs.values()) { stoppable.stop() } this.cronJobs.clear() + this.isStarted = false } registerJob(job: ScheduleJob): void { diff --git a/backend/src/utils/proxy-timeout.ts b/backend/src/utils/proxy-timeout.ts index 5453bb18..df6f7ea2 100644 --- a/backend/src/utils/proxy-timeout.ts +++ b/backend/src/utils/proxy-timeout.ts @@ -2,8 +2,12 @@ import { DEFAULTS } from '@opencode-manager/shared/config/defaults' export const PROXY_REQUEST_TIMEOUT_MS = DEFAULTS.PROXY.REQUEST_TIMEOUT_MS +const STREAMING_PATHS = new Set(['/event', '/global/event']) +const STREAMING_SUFFIXES = ['/event'] + export function isStreamingPath(pathname: string): boolean { - return pathname.endsWith('/event') + if (STREAMING_PATHS.has(pathname)) return true + return STREAMING_SUFFIXES.some((s) => pathname.endsWith(s)) } export function buildFetchSignal(pathname: string, timeoutMs: number = PROXY_REQUEST_TIMEOUT_MS): AbortSignal | undefined { diff --git a/backend/test/routes/workspace-plugin.test.ts b/backend/test/routes/workspace-plugin.test.ts index 9866ca31..deb5783a 100644 --- a/backend/test/routes/workspace-plugin.test.ts +++ b/backend/test/routes/workspace-plugin.test.ts @@ -1,4 +1,4 @@ -import { describe, it, expect, beforeEach, vi } from 'vitest' +import { describe, it, expect, beforeEach } from 'vitest' import { Hono } from 'hono' import { Database } from 'bun:sqlite' import { createAuth } from '../../src/auth' @@ -89,116 +89,4 @@ describe('Workspace Plugin Routes', () => { expect(res.status).toBe(403) }) }) - - describe('ALL /opencode/:slug/*', () => { - it('returns 401 without session', async () => { - const app = new Hono<{ Variables: AppVariables }>() - app.use('/api/workspace-plugin/*', createAuthMiddleware(auth, apiTokenService, db)) - app.route('/api/workspace-plugin', createWorkspacePluginRoutes(db)) - - const res = await app.request('http://localhost/api/workspace-plugin/opencode/42/session') - - expect(res.status).toBe(401) - }) - - it('returns 403 with insufficient token scope', async () => { - seedUser(db, 'user-123') - const tokenResult = apiTokenService.create('user-123', 'test-token', 'other-scope') - - const app = new Hono<{ Variables: AppVariables }>() - app.use('/api/workspace-plugin/*', createAuthMiddleware(auth, apiTokenService, db)) - app.route('/api/workspace-plugin', createWorkspacePluginRoutes(db)) - - const res = await app.request('http://localhost/api/workspace-plugin/opencode/42/session', { - headers: { Authorization: `Bearer ${tokenResult.token}` }, - }) - - expect(res.status).toBe(403) - }) - - it('returns 404 for unknown slug', async () => { - seedUser(db, 'user-123') - const tokenResult = apiTokenService.create('user-123', 'test-token', 'workspace-plugin') - - const app = new Hono<{ Variables: AppVariables }>() - app.use('/api/workspace-plugin/*', createAuthMiddleware(auth, apiTokenService, db)) - app.route('/api/workspace-plugin', createWorkspacePluginRoutes(db)) - - const res = await app.request('http://localhost/api/workspace-plugin/opencode/unknown-slug/session', { - headers: { Authorization: `Bearer ${tokenResult.token}` }, - }) - - expect(res.status).toBe(404) - }) - - it('forwards request to upstream with directory query param', async () => { - seedUser(db, 'user-123') - seedRepo(db, 42, 'my-repo', undefined, '/workspace/repos/my-repo') - const tokenResult = apiTokenService.create('user-123', 'test-token', 'workspace-plugin') - - const mockFetch = vi.spyOn(globalThis, 'fetch').mockImplementation(async (input) => { - const url = typeof input === 'string' ? input : 'url' in input ? input.url : '' - void url - return new Response(JSON.stringify({ success: true }), { - status: 200, - headers: { 'Content-Type': 'application/json' }, - }) - }) - - try { - const app = new Hono<{ Variables: AppVariables }>() - app.use('/api/workspace-plugin/*', createAuthMiddleware(auth, apiTokenService, db)) - app.route('/api/workspace-plugin', createWorkspacePluginRoutes(db)) - - const res = await app.request('http://localhost/api/workspace-plugin/opencode/42/session', { - headers: { Authorization: `Bearer ${tokenResult.token}` }, - }) - - expect(res.status).toBe(200) - - expect(mockFetch).toHaveBeenCalled() - const calledUrl = mockFetch.mock.calls[0]?.[0] as string - expect(calledUrl).toContain('directory=%2Fworkspace%2Frepos%2Fmy-repo') - expect(calledUrl).toMatch(/\/session/) - } finally { - mockFetch.mockRestore() - } - }) - - it('forwards POST body to upstream', async () => { - seedUser(db, 'user-123') - seedRepo(db, 42, 'my-repo', undefined, '/workspace/repos/my-repo') - const tokenResult = apiTokenService.create('user-123', 'test-token', 'workspace-plugin') - - const mockFetch = vi.spyOn(globalThis, 'fetch').mockImplementation(async (input) => { - void input - return new Response(JSON.stringify({ success: true }), { - status: 200, - headers: { 'Content-Type': 'application/json' }, - }) - }) - - try { - const app = new Hono<{ Variables: AppVariables }>() - app.use('/api/workspace-plugin/*', createAuthMiddleware(auth, apiTokenService, db)) - app.route('/api/workspace-plugin', createWorkspacePluginRoutes(db)) - - const body = JSON.stringify({ action: 'test' }) - await app.request('http://localhost/api/workspace-plugin/opencode/42/session/action', { - method: 'POST', - headers: { - Authorization: `Bearer ${tokenResult.token}`, - 'Content-Type': 'application/json', - }, - body, - }) - - expect(mockFetch).toHaveBeenCalled() - const calledInit = mockFetch.mock.calls[0]?.[1] as RequestInit - expect(calledInit?.body).toBeDefined() - } finally { - mockFetch.mockRestore() - } - }) - }) }) diff --git a/backend/test/services/proxy-ws.test.ts b/backend/test/services/proxy-ws.test.ts index eb940d3f..f3481369 100644 --- a/backend/test/services/proxy-ws.test.ts +++ b/backend/test/services/proxy-ws.test.ts @@ -1,10 +1,6 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest' import { EventEmitter } from 'node:events' -vi.mock('bun:sqlite', () => ({ - Database: vi.fn(), -})) - vi.mock('@opencode-manager/shared/config/env', () => ({ ENV: { OPENCODE: { PORT: 5551, HOST: '127.0.0.1' }, @@ -62,19 +58,19 @@ function createMockServer() { } } -async function triggerUpgrade(options?: { slug?: string }) { +async function triggerUpgrade() { const { attachWorkspacePluginWs } = await import('../../src/services/proxy-ws') const { server, emitter } = createMockServer() const socket = createMockSocket() + const mockReq = { - url: '/api/opencode/test', - headers: options?.slug ? { 'x-opencode-manager-project': options.slug } : {}, + url: `/api/opencode/test`, + headers: {}, } as unknown as Parameters[0] extends never ? never : unknown attachWorkspacePluginWs(server as Parameters[0], { upstreamBaseUrl: 'http://127.0.0.1:5551', verifyAuth: vi.fn().mockResolvedValue({ userId: 'u', scope: 's' }), - projectService: options?.slug ? { getBySlug: vi.fn(() => ({ directory: '/test' })) } : undefined, }) emitter.emit('upgrade', mockReq, socket, Buffer.from([])) diff --git a/backend/test/services/proxy.test.ts b/backend/test/services/proxy.test.ts index eaef8471..aac710c7 100644 --- a/backend/test/services/proxy.test.ts +++ b/backend/test/services/proxy.test.ts @@ -443,80 +443,4 @@ describe('proxy service', () => { }) }) - describe('proxyRequest timeout', () => { - const originalFetch = global.fetch - - beforeEach(() => { - vi.clearAllMocks() - }) - - afterEach(() => { - global.fetch = originalFetch - }) - - it('applies AbortSignal.timeout to non-streaming requests', async () => { - let capturedSignal: AbortSignal | undefined - - const mockResponse = new Response('OK', { status: 200 }) - - global.fetch = vi.fn((url, options) => { - capturedSignal = options?.signal as AbortSignal - return Promise.resolve(mockResponse) - }) as unknown as typeof fetch - - const { proxyRequest } = await import('../../src/services/proxy') - - const mockRequest = new Request('http://localhost:5003/api/opencode/test') - await proxyRequest(mockRequest) - - expect(capturedSignal).toBeDefined() - expect(capturedSignal).toBeInstanceOf(AbortSignal) - }) - - it('does not apply timeout to streaming /event path', async () => { - const mockStream = new ReadableStream({ - start(controller) { - controller.enqueue(new TextEncoder().encode('data: test\n\n')) - controller.close() - }, - }) - - const mockResponse = new Response(mockStream, { - status: 200, - headers: { 'Content-Type': 'text/event-stream' }, - }) - - global.fetch = vi.fn().mockResolvedValue(mockResponse) as unknown as typeof fetch - - const { proxyRequest } = await import('../../src/services/proxy') - - const mockRequest = new Request('http://localhost:5003/api/opencode/event?directory=/test') - const response = await proxyRequest(mockRequest) - - expect(response.status).toBe(200) - expect(response.headers.get('Content-Type')).toBe('text/event-stream') - }) - - it('forwards Authorization via withOpenCodeAuth', async () => { - let capturedHeaders: Record | undefined - - const mockResponse = new Response('OK', { status: 200 }) - - global.fetch = vi.fn((url, options) => { - capturedHeaders = options?.headers as Record - return Promise.resolve(mockResponse) - }) as unknown as typeof fetch - - const { proxyRequest } = await import('../../src/services/proxy') - - const mockRequest = new Request('http://localhost:5003/api/opencode/test', { - method: 'POST', - body: 'test', - }) - - await proxyRequest(mockRequest) - - expect(capturedHeaders).toBeDefined() - }) - }) }) diff --git a/backend/test/services/schedules.test.ts b/backend/test/services/schedules.test.ts index f29d37a2..b968b347 100644 --- a/backend/test/services/schedules.test.ts +++ b/backend/test/services/schedules.test.ts @@ -1108,4 +1108,36 @@ describe('ScheduleRunner', () => { expect(mockCronStop).toHaveBeenCalled() expect(mockCronInstances).toHaveLength(2) }) + + it('keeps runner start idempotent when called multiple times', async () => { + const mockJob: ScheduleJob = { + id: 6, + repoId: 10, + name: 'Idempotent Start', + description: null, + enabled: true, + scheduleMode: 'interval', + intervalMinutes: 60, + cronExpression: null, + timezone: null, + agentSlug: null, + prompt: 'Test', + model: null, + skillMetadata: null, + nextRunAt: Date.now(), + lastRunAt: null, + createdAt: Date.now(), + updatedAt: Date.now(), + } + mocks.listRunningScheduleRuns.mockReturnValue([]) + mocks.listEnabledScheduleJobs.mockReturnValue([mockJob]) + + const service = new ScheduleService({} as never) + const runner = new ScheduleRunner(service) + await runner.start() + await runner.start() + + expect(mockCronInstances).toHaveLength(1) + expect(mockCronStop).not.toHaveBeenCalled() + }) }) diff --git a/backend/test/utils/proxy-timeout.test.ts b/backend/test/utils/proxy-timeout.test.ts new file mode 100644 index 00000000..94923980 --- /dev/null +++ b/backend/test/utils/proxy-timeout.test.ts @@ -0,0 +1,52 @@ +import { describe, it, expect } from 'vitest' +import { isStreamingPath, buildFetchSignal } from '../../src/utils/proxy-timeout' + +describe('isStreamingPath', () => { + it('returns true for /event', () => { + expect(isStreamingPath('/event')).toBe(true) + }) + + it('returns true for /global/event', () => { + expect(isStreamingPath('/global/event')).toBe(true) + }) + + it('returns true for /session/X/event', () => { + expect(isStreamingPath('/session/abc123/event')).toBe(true) + }) + + it('returns false for /sync/history', () => { + expect(isStreamingPath('/sync/history')).toBe(false) + }) + + it('returns false for /config', () => { + expect(isStreamingPath('/config')).toBe(false) + }) + + it('returns false for /', () => { + expect(isStreamingPath('/')).toBe(false) + }) + + it('returns false for /session/X/config', () => { + expect(isStreamingPath('/session/abc123/config')).toBe(false) + }) +}) + +describe('buildFetchSignal', () => { + it('returns undefined for streaming paths', () => { + expect(buildFetchSignal('/event')).toBeUndefined() + expect(buildFetchSignal('/global/event')).toBeUndefined() + expect(buildFetchSignal('/session/abc/event')).toBeUndefined() + }) + + it('returns AbortSignal for non-streaming paths', () => { + const signal = buildFetchSignal('/config') + expect(signal).toBeDefined() + expect(signal).toBeInstanceOf(AbortSignal) + }) + + it('uses custom timeout when provided', () => { + const customTimeout = 5000 + const signal = buildFetchSignal('/config', customTimeout) + expect(signal).toBeDefined() + }) +}) diff --git a/docs/features/workspace-plugin.md b/docs/features/workspace-plugin.md index 5b0048db..4bcdf099 100644 --- a/docs/features/workspace-plugin.md +++ b/docs/features/workspace-plugin.md @@ -1,43 +1,42 @@ # Workspace Plugin -The workspace plugin allows you to connect your local OpenCode TUI to a running opencode-manager instance and use its projects as remote workspaces. +The workspace plugin connects a local OpenCode TUI to a running opencode-manager instance and exposes its projects as local workspaces. ## Overview -The workspace plugin consists of two main components: +The plugin uses the manager **only** to discover the list of projects. Once projects are registered, all runtime traffic (sessions, messages, SSE, WebSockets) flows through the in-process opencode server. The manager is not a proxy for OpenCode traffic. -1. **Manager-side**: Backend endpoints and authentication for serving project information -2. **Plugin**: An OpenCode plugin that connects to the manager and registers remote workspaces +Two components: + +1. **Manager-side**: `GET /api/workspace-plugin/projects` endpoint plus bearer-token auth. +2. **Plugin** (`@opencode-manager/workspace-plugin`): An OpenCode plugin that calls the manager at startup, then configures each workspace with the project's local directory. ## Features -- **Bearer Token Authentication**: Secure API tokens for external access -- **Project Discovery**: Automatically discover and register all manager projects -- **Remote Workspace Support**: Use manager projects as remote workspaces in OpenCode TUI -- **SSE Streaming**: Server-sent events are properly streamed (not buffered) -- **WebSocket Support**: WebSocket connections are proxied correctly +- Bearer token auth for manager discovery. +- Local workspace targeting — all session ops run in-process against the repository directory. +- Native SSE and WebSocket support via the opencode server. ## Setup ### 1. Create an API Token -1. Open your opencode-manager web UI -2. Navigate to Settings → API Tokens -3. Click "Create Token" -4. Give it a descriptive name (e.g., "OpenCode TUI") -5. **Copy the token immediately** - it won't be shown again -6. Store the token securely +1. Open your opencode-manager web UI. +2. Navigate to Settings → API Tokens. +3. Click "Create Token". +4. Give it a descriptive name (e.g., "OpenCode TUI"). +5. **Copy the token immediately** — it won't be shown again. ### 2. Install the Plugin -In your OpenCode configuration (`opencode.json`), add: +In your OpenCode configuration (`opencode.json`): ```json { "plugin": [ ["@opencode-manager/workspace-plugin", { "url": "http://localhost:5003", - "token": "" + "token": "" }] ] } @@ -47,22 +46,25 @@ Or use environment variables: ```bash export OPENCODE_MANAGER_URL="http://localhost:5003" -export OPENCODE_MANAGER_TOKEN="" +export OPENCODE_MANAGER_TOKEN="" ``` ### 3. Start OpenCode TUI -Launch the OpenCode TUI. You should see your manager projects appear in the workspace picker as `manager:`. +Launch the TUI and attach to the manager's opencode server: + +```bash +opencode attach http://localhost:5551 +``` + +Manager projects appear in the workspace picker as `manager:`. ## How It Works -1. **Plugin Initialization**: When OpenCode starts, the plugin calls `GET /api/workspace-plugin/projects` on the manager -2. **Project Registration**: For each project returned, the plugin registers a `WorkspaceAdaptor` with type `manager:` -3. **Workspace Selection**: When you select a workspace in the TUI, the adaptor provides: - - Remote target URL: `/api/opencode` - - Authorization header: `Bearer ` - - Project slug header: `x-opencode-manager-project: ` -4. **Request Proxying**: The manager proxies requests to the embedded OpenCode server with the appropriate `?directory=` parameter +1. **Discovery**: The plugin calls `GET /api/workspace-plugin/projects` on the manager with the bearer token. +2. **Registration**: For each project returned, the plugin registers a `WorkspaceAdaptor` as `manager:`. +3. **Selection**: When the user picks a workspace, the adaptor returns `{ type: "local", directory: project.directory }`. +4. **Runtime**: The opencode server uses the directory to scope the session to that project's repository. All operations run in-process against the local filesystem. ## API Reference @@ -70,7 +72,7 @@ Launch the OpenCode TUI. You should see your manager projects appear in the work Returns a list of projects available in the manager. -**Authentication**: Bearer token or session cookie +**Authentication**: Bearer token with `workspace-plugin` or `*` scope. **Response**: ```json @@ -90,43 +92,9 @@ Returns a list of projects available in the manager. List all API tokens for the current user. -**Response**: -```json -{ - "tokens": [ - { - "id": "uuid", - "name": "token-name", - "scope": "workspace-plugin", - "lastUsedAt": 1234567890, - "createdAt": 1234567890, - "expiresAt": null - } - ] -} -``` - ### `POST /api/settings/tokens` -Create a new API token. - -**Request**: -```json -{ - "name": "token-name", - "scope": "workspace-plugin", - "expiresAt": 1234567890 -} -``` - -**Response**: -```json -{ - "id": "uuid", - "name": "token-name", - "token": "raw-token-shown-once" -} -``` +Create a new API token. The raw token is returned in the response only once. ### `DELETE /api/settings/tokens/:id` @@ -134,39 +102,35 @@ Revoke an API token. ## Security Considerations -- **Token Storage**: Tokens are stored as SHA-256 hashes in the database -- **One-Time Display**: Raw tokens are shown only once on creation -- **Token Revocation**: Tokens can be revoked at any time from the Settings UI -- **Scope Restriction**: Tokens have a `workspace-plugin` scope by default -- **CORS Bypass**: Bearer tokens bypass CORS origin requirements (explicit opt-in) +- **Token storage**: Manager tokens are stored as SHA-256 hashes. +- **One-time display**: Raw tokens are shown only once. +- **Scope restriction**: Default `workspace-plugin` scope grants access only to `/api/workspace-plugin/*`. ## Token Scopes -- `workspace-plugin`: Access to workspace plugin endpoints (default) -- `*`: Full access to all protected endpoints +- `workspace-plugin`: Access to `/api/workspace-plugin/*` (default). +- `*`: Full access to all protected endpoints. ## Troubleshooting ### Plugin fails to connect -1. Verify the manager URL is correct and accessible -2. Check that the token is valid and not expired -3. Ensure the token has the correct scope (`workspace-plugin`) -4. Check the manager logs for authentication errors +1. Verify the manager URL is correct and reachable. +2. Check that the token is valid and not expired. +3. Ensure the token scope is `workspace-plugin` or `*`. +4. Check the manager logs for authentication errors. ### Projects don't appear -1. Verify the manager has projects configured -2. Check that the token has not been revoked -3. Look for errors in the OpenCode TUI console +1. Verify the manager has projects configured. +2. Check that the token has not been revoked. +3. Look for errors in the OpenCode TUI plugin logs. -### SSE events not streaming +### Session operations fail after project shows up -The proxy has been updated to stream response bodies instead of buffering. If you experience issues: - -1. Check that the manager is running the latest version -2. Verify the upstream OpenCode server is sending proper SSE headers -3. Look for buffering in network inspection tools +1. Verify the project directory exists on the local filesystem. +2. Check that the directory is accessible and has proper permissions. +3. Look for errors in the opencode server logs. ## Development diff --git a/packages/workspace-plugin/README.md b/packages/workspace-plugin/README.md index da11db65..655c70c3 100644 --- a/packages/workspace-plugin/README.md +++ b/packages/workspace-plugin/README.md @@ -1,6 +1,8 @@ # @opencode-manager/workspace-plugin -Connect your local OpenCode TUI to a running opencode-manager instance and use its projects as remote workspaces. +Connect your local OpenCode TUI to a running opencode-manager instance and use its projects as local workspaces. + +The plugin queries the manager for the list of projects, then configures each workspace to use the project's local directory. The manager is only used for project discovery; all session operations run in-process against the local repository. ## Installation @@ -21,19 +23,19 @@ Add the plugin to your `opencode.json` configuration: ### Options -- `url` (required): The base URL of your opencode-manager instance -- `token` (required): Bearer token created from the manager's Settings page +- `url` (required): Base URL of your opencode-manager instance. Used only to fetch the project list. +- `token` (required): Bearer token created from the manager's Settings page. ### Environment Variables -As an alternative to configuring in `opencode.json`, you can use: +As an alternative to configuring in `opencode.json`: -- `OPENCODE_MANAGER_URL`: The base URL of your opencode-manager instance -- `OPENCODE_MANAGER_TOKEN`: Bearer token for authentication +- `OPENCODE_MANAGER_URL`: Base URL of your opencode-manager instance +- `OPENCODE_MANAGER_TOKEN`: Bearer token for manager discovery ## Usage -Once configured, the plugin will automatically discover all projects in your opencode-manager instance and register them as remote workspaces. Each project will appear in the OpenCode TUI workspace picker as `manager:`. +Once configured, the plugin will discover all projects in your opencode-manager instance and register them as local workspaces. Each project appears in the OpenCode TUI workspace picker as `manager:`. ### Creating a Bearer Token @@ -46,22 +48,32 @@ Once configured, the plugin will automatically discover all projects in your ope ### Token Scope -Tokens created for the workspace plugin have the `workspace-plugin` scope by default. This restricts their access to only the workspace plugin endpoints. +Tokens created for the workspace plugin have the `workspace-plugin` scope by default. This restricts their access to the `/api/workspace-plugin/projects` endpoint. + +### Using the TUI + +After starting the opencode-manager server, connect the TUI with: + +```bash +opencode attach http://localhost:5551 +``` + +Select a workspace from the manager's project list. Each workspace is rooted at the project's local repository directory. ## How It Works -1. On startup, the plugin calls `GET /api/workspace-plugin/projects` on the manager -2. For each project returned, it registers a `WorkspaceAdaptor` with type `manager:` -3. When you select a workspace in the TUI, the adaptor provides: - - Remote target URL: `/api/opencode` - - Authorization header: `Bearer ` - - Project slug header: `x-opencode-manager-project: ` +1. On startup, the plugin calls `GET /api/workspace-plugin/projects` on the manager to enumerate projects. +2. For each project, it registers a `WorkspaceAdaptor` as `manager:`. +3. When the user selects a workspace, the adaptor returns a `type: "local"` target with the project's directory. +4. All session/message/event traffic flows through the in-process opencode server, scoped to the project's directory. -The manager then proxies requests to the embedded OpenCode server with the appropriate `?directory=` parameter. +### TUI pre-warming + +The package also ships a TUI plugin (`./tui` subpath) that opencode loads alongside the server plugin. It listens for `session.created` and `workspace.status` events, and when a `manager:*` workspace becomes active it pre-fetches the workspace-scoped endpoints (`config`, `providers`, `agents`, `commands`, `vcs`, `session.status`, etc.) so that the TUI's own `sync.bootstrap` resolves from warm server-side state. + +This avoids the race where a newly created workspace appears empty on the first session open and only renders correctly after navigating back and re-entering. No user configuration is required — the single `plugin` entry in `opencode.json` activates both halves. ## Security Notes -- Bearer tokens are stored hashed (SHA-256) in the manager database -- Tokens are shown only once on creation -- Tokens can be revoked at any time from the Settings page -- Tokens bypass CORS origin requirements (explicit opt-in authentication) +- The manager bearer token is only used for project discovery. It never reaches the opencode server. +- Manager bearer tokens are stored hashed (SHA-256) in the manager database and shown only once on creation. diff --git a/packages/workspace-plugin/package.json b/packages/workspace-plugin/package.json index fd188401..6c141e12 100644 --- a/packages/workspace-plugin/package.json +++ b/packages/workspace-plugin/package.json @@ -5,7 +5,18 @@ "main": "./dist/index.js", "types": "./dist/index.d.ts", "exports": { - ".": "./dist/index.js" + ".": { + "import": "./dist/index.js", + "types": "./dist/index.d.ts" + }, + "./server": { + "import": "./dist/index.js", + "types": "./dist/index.d.ts" + }, + "./tui": { + "import": "./dist/tui.js", + "types": "./dist/tui.d.ts" + } }, "peerDependencies": { "@opencode-ai/plugin": ">=1.14.0", diff --git a/packages/workspace-plugin/src/index.ts b/packages/workspace-plugin/src/index.ts index 11ec16e7..8076601d 100644 --- a/packages/workspace-plugin/src/index.ts +++ b/packages/workspace-plugin/src/index.ts @@ -1,9 +1,14 @@ -import type { Plugin, WorkspaceAdaptor, WorkspaceInfo } from "@opencode-ai/plugin" +import type { Plugin, PluginInput, WorkspaceAdaptor, WorkspaceInfo } from "@opencode-ai/plugin" import { ManagerClient } from "./client.js" import { pluginLogger } from "./logger.js" import { PluginOptionsSchema, type ManagerProject } from "./types.js" -export function resolveConfig(options: unknown): { url: string; token: string } { +export interface ResolvedConfig { + url: string + token: string +} + +export function resolveConfig(options: unknown): ResolvedConfig { const parsed = PluginOptionsSchema.parse(options ?? {}) const url = parsed.url ?? process.env.OPENCODE_MANAGER_URL const token = parsed.token ?? process.env.OPENCODE_MANAGER_TOKEN @@ -12,55 +17,64 @@ export function resolveConfig(options: unknown): { url: string; token: string } return { url, token } } -export function makeAdaptor(cfg: { url: string; token: string }, project: ManagerProject): WorkspaceAdaptor { +export function makeAdaptor(cfg: ResolvedConfig, project: ManagerProject): WorkspaceAdaptor { return { name: `Manager: ${project.name}`, - description: `Connect to the "${project.name}" project on opencode-manager at ${cfg.url}`, + description: `Connect to the "${project.name}" project`, configure(info: WorkspaceInfo) { - const result = { ...info, name: project.name, directory: project.directory, extra: { slug: project.slug } } - pluginLogger.info( - `adaptor.configure slug=${project.slug} input=${JSON.stringify(info)} output=${JSON.stringify(result)}`, - ) - return result + pluginLogger.info(`adaptor.configure slug=${project.slug} workspaceID=${info.id} dir=${project.directory}`) + return { + ...info, + name: project.name, + directory: project.directory, + extra: { slug: project.slug }, + } }, - async create(info, env) { - pluginLogger.info( - `adaptor.create slug=${project.slug} info=${JSON.stringify(info)} env_keys=${Object.keys(env ?? {}).join(",")}`, - ) + async create(info) { + pluginLogger.info(`adaptor.create slug=${project.slug} workspaceID=${info.id} dir=${project.directory}`) }, async remove(info) { - pluginLogger.info(`adaptor.remove slug=${project.slug} info=${JSON.stringify(info)}`) + pluginLogger.info(`adaptor.remove slug=${project.slug} workspaceID=${info.id}`) }, target(info) { - const base = cfg.url.replace(/\/$/, "") - const url = `${base}/api/workspace-plugin/opencode/${encodeURIComponent(project.slug)}` - const result = { - type: "remote" as const, - url, - headers: { Authorization: `Bearer ${cfg.token}` }, - } - pluginLogger.info( - `adaptor.target slug=${project.slug} input=${JSON.stringify(info)} output=${JSON.stringify({ type: result.type, url: result.url })}`, - ) - return result + pluginLogger.info(`adaptor.target slug=${project.slug} workspaceID=${info.id} dir=${project.directory}`) + return { type: "local" as const, directory: project.directory } }, } } -export const OpencodeManagerWorkspacePlugin: Plugin = async ({ experimental_workspace }, options) => { +const prewarmed = new Set() + +async function prewarmProject(input: PluginInput, project: ManagerProject): Promise { + if (prewarmed.has(project.directory)) return + prewarmed.add(project.directory) + const start = Date.now() + try { + await input.client.project.current({ query: { directory: project.directory } }) + pluginLogger.info( + `prewarm.ok slug=${project.slug} dir=${project.directory} elapsed_ms=${Date.now() - start}`, + ) + } catch (error) { + prewarmed.delete(project.directory) + pluginLogger.warn( + `prewarm.failed slug=${project.slug} dir=${project.directory} elapsed_ms=${Date.now() - start}`, + error, + ) + } +} + +export const OpencodeManagerWorkspacePlugin: Plugin = async (input, options) => { try { const cfg = resolveConfig(options) - pluginLogger.info( - `plugin.init url=${cfg.url} env.OPENCODE_EXPERIMENTAL_WORKSPACES=${process.env.OPENCODE_EXPERIMENTAL_WORKSPACES ?? "unset"} env.OPENCODE_EXPERIMENTAL=${process.env.OPENCODE_EXPERIMENTAL ?? "unset"}`, - ) + pluginLogger.info(`plugin.init url=${cfg.url}`) const client = new ManagerClient(cfg.url, cfg.token) const projects = await client.listProjects() pluginLogger.info(`plugin.init loaded ${projects.length} project(s)`) for (const project of projects) { - pluginLogger.info(`plugin.register slug=${project.slug} name=${project.name}`) - experimental_workspace.register(`manager:${project.slug}`, makeAdaptor(cfg, project)) + input.experimental_workspace.register(`manager:${project.slug}`, makeAdaptor(cfg, project)) } pluginLogger.info(`plugin.ready`) + void Promise.all(projects.map((project) => prewarmProject(input, project))) return {} } catch (error) { pluginLogger.error(`plugin.init failed`, error) diff --git a/packages/workspace-plugin/src/tui.ts b/packages/workspace-plugin/src/tui.ts new file mode 100644 index 00000000..8f087742 --- /dev/null +++ b/packages/workspace-plugin/src/tui.ts @@ -0,0 +1,144 @@ +import type { TuiPlugin, TuiPluginApi } from "@opencode-ai/plugin/tui" +import { pluginLogger } from "./logger.js" + +const MANAGER_WORKSPACE_PREFIX = "manager:" + +type WorkspaceRecord = { + id: string + type: string +} + +type PrewarmResult = { + ok: number + failed: number + durationMs: number +} + +async function prewarmWorkspace(api: TuiPluginApi, workspaceID: string): Promise { + const started = Date.now() + const client = api.client + const scoped = { workspace: workspaceID } + + const tasks: Array<{ name: string; run: () => Promise }> = [ + { name: "config.get", run: () => client.config.get(scoped) }, + { name: "config.providers", run: () => client.config.providers(scoped) }, + { name: "provider.list", run: () => client.provider.list(scoped) }, + { name: "provider.auth", run: () => client.provider.auth(scoped) }, + { name: "app.agents", run: () => client.app.agents(scoped) }, + { name: "command.list", run: () => client.command.list(scoped) }, + { name: "vcs.get", run: () => client.vcs.get(scoped) }, + { name: "session.status", run: () => client.session.status(scoped) }, + { name: "lsp.status", run: () => client.lsp.status(scoped) }, + { name: "formatter.status", run: () => client.formatter.status(scoped) }, + ] + + const outcomes = await Promise.all( + tasks.map(async (task) => { + try { + await task.run() + return true + } catch (error) { + pluginLogger.warn(`tui.prewarm task failed workspaceID=${workspaceID} task=${task.name}`, error) + return false + } + }), + ) + + const ok = outcomes.filter(Boolean).length + return { ok, failed: outcomes.length - ok, durationMs: Date.now() - started } +} + +async function refreshWorkspaceIndex(api: TuiPluginApi, index: Map): Promise { + try { + const res = await api.client.experimental.workspace.list() + const list = res.data ?? [] + index.clear() + for (const item of list) { + if (typeof item.id !== "string" || typeof item.type !== "string") continue + index.set(item.id, { id: item.id, type: item.type }) + } + pluginLogger.info(`tui.workspaceIndex refreshed count=${index.size}`) + } catch (error) { + pluginLogger.warn(`tui.workspaceIndex refresh failed`, error) + } +} + +function isManagerWorkspace(record: WorkspaceRecord | undefined): boolean { + return !!record && record.type.startsWith(MANAGER_WORKSPACE_PREFIX) +} + +export const OpencodeManagerWorkspaceTuiPlugin: TuiPlugin = async (api) => { + pluginLogger.info(`tui.init`) + + const workspaceIndex = new Map() + const inflight = new Map>() + + const runPrewarm = (workspaceID: string, reason: string) => { + const existing = inflight.get(workspaceID) + if (existing) return existing + + pluginLogger.info(`tui.prewarm start workspaceID=${workspaceID} reason=${reason}`) + const task = prewarmWorkspace(api, workspaceID) + .then((result) => { + pluginLogger.info( + `tui.prewarm done workspaceID=${workspaceID} reason=${reason} ok=${result.ok} failed=${result.failed} durationMs=${result.durationMs}`, + ) + return result + }) + .finally(() => { + inflight.delete(workspaceID) + }) + + inflight.set(workspaceID, task) + return task + } + + await refreshWorkspaceIndex(api, workspaceIndex) + + const offSessionCreated = api.event.on("session.created", (event) => { + const workspaceID = event.properties.info.workspaceID + if (!workspaceID) return + + const record = workspaceIndex.get(workspaceID) + if (isManagerWorkspace(record)) { + void runPrewarm(workspaceID, "session.created") + return + } + + void refreshWorkspaceIndex(api, workspaceIndex).then(() => { + const refreshed = workspaceIndex.get(workspaceID) + if (isManagerWorkspace(refreshed)) { + void runPrewarm(workspaceID, "session.created:after-refresh") + } + }) + }) + + const offWorkspaceStatus = api.event.on("workspace.status", (event) => { + const { workspaceID, status } = event.properties + if (status !== "connected") return + + const record = workspaceIndex.get(workspaceID) + if (isManagerWorkspace(record)) { + void runPrewarm(workspaceID, "workspace.status:connected") + return + } + + void refreshWorkspaceIndex(api, workspaceIndex).then(() => { + const refreshed = workspaceIndex.get(workspaceID) + if (isManagerWorkspace(refreshed)) { + void runPrewarm(workspaceID, "workspace.status:connected:after-refresh") + } + }) + }) + + api.lifecycle.onDispose(() => { + offSessionCreated() + offWorkspaceStatus() + pluginLogger.info(`tui.dispose`) + }) +} + +export default { + id: "opencode-manager-workspace", + tui: OpencodeManagerWorkspaceTuiPlugin, +} diff --git a/packages/workspace-plugin/test/index.test.ts b/packages/workspace-plugin/test/index.test.ts index b4931965..e8b8ec94 100644 --- a/packages/workspace-plugin/test/index.test.ts +++ b/packages/workspace-plugin/test/index.test.ts @@ -1,4 +1,4 @@ -import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest' +import { describe, it, expect, beforeEach, afterEach } from 'vitest' import { PluginOptionsSchema } from '../src/types' import { resolveConfig } from '../src/index' import type { WorkspaceInfo } from '@opencode-ai/plugin' @@ -14,6 +14,12 @@ describe('PluginOptionsSchema', () => { expect(parsed.token).toBe('test-token') }) + it('ignores unknown fields', () => { + const parsed = PluginOptionsSchema.parse({ url: 'http://test.com', token: 'test', unknownField: 'ignored' }) + expect(parsed.url).toBe('http://test.com') + expect(parsed.token).toBe('test') + }) + it('requires token to be non-empty', () => { expect(() => PluginOptionsSchema.parse({ token: '' })).toThrow() }) @@ -40,8 +46,14 @@ describe('resolveConfig', () => { }) it('uses options when provided', () => { - const cfg = resolveConfig({ url: 'http://options.com', token: 'options-token' }) - expect(cfg).toEqual({ url: 'http://options.com', token: 'options-token' }) + const cfg = resolveConfig({ + url: 'http://options.com', + token: 'options-token', + }) + expect(cfg).toEqual({ + url: 'http://options.com', + token: 'options-token', + }) }) it('falls back to env vars when options omit fields', () => { @@ -49,15 +61,24 @@ describe('resolveConfig', () => { process.env.OPENCODE_MANAGER_TOKEN = 'env-token' const cfg = resolveConfig({}) - expect(cfg).toEqual({ url: 'http://env.com', token: 'env-token' }) + expect(cfg).toEqual({ + url: 'http://env.com', + token: 'env-token', + }) }) it('prefers options over env vars when both present', () => { process.env.OPENCODE_MANAGER_URL = 'http://env.com' process.env.OPENCODE_MANAGER_TOKEN = 'env-token' - const cfg = resolveConfig({ url: 'http://options.com', token: 'options-token' }) - expect(cfg).toEqual({ url: 'http://options.com', token: 'options-token' }) + const cfg = resolveConfig({ + url: 'http://options.com', + token: 'options-token', + }) + expect(cfg).toEqual({ + url: 'http://options.com', + token: 'options-token', + }) }) it('throws when url missing from both options and env', () => { @@ -78,32 +99,56 @@ describe('adaptor.target', () => { extra: {}, } - it('returns { type: "remote", url, headers } with bearer auth when target is invoked', async () => { + const baseCfg = { + url: 'http://manager.test:5003', + token: 'tok-abc', + } + + it('returns { type: "local", directory: project.directory }', async () => { const { makeAdaptor } = await import('../src/index.js') - const cfg = { url: 'http://manager.test:5003', token: 'tok-abc' } const project = { slug: '42', name: 'Test Project', directory: '/workspace/repos/test' } - const adaptor = makeAdaptor(cfg, project) + const adaptor = makeAdaptor(baseCfg, project) const result = adaptor.target(sampleInfo) - expect(result.type).toBe('remote') - expect(result.url).toBe('http://manager.test:5003/api/workspace-plugin/opencode/42') - expect(result.headers).toEqual({ Authorization: 'Bearer tok-abc' }) + expect(result.type).toBe('local') + expect(result.directory).toBe('/workspace/repos/test') }) - it('url-encodes special slug characters', async () => { + it('returns directory from project, not from info', async () => { const { makeAdaptor } = await import('../src/index.js') - const cfg = { url: 'http://manager.test:5003', token: 'tok-abc' } - const project = { slug: 'a/b c', name: 'Test Project', directory: '/workspace/repos/test' } - const adaptor = makeAdaptor(cfg, project) - const result = adaptor.target(sampleInfo) - expect(result.url).toContain('a%2Fb%20c') - }) - - it('strips trailing slash from manager url', async () => { - const { makeAdaptor } = await import('../src/index.js') - const cfg = { url: 'http://manager.test:5003/', token: 'tok-abc' } const project = { slug: '42', name: 'Test Project', directory: '/workspace/repos/test' } - const adaptor = makeAdaptor(cfg, project) + const adaptor = makeAdaptor(baseCfg, project) const result = adaptor.target(sampleInfo) - expect(result.url).toBe('http://manager.test:5003/api/workspace-plugin/opencode/42') + expect(result.directory).toBe('/workspace/repos/test') }) }) + +describe('adaptor.configure', () => { + const sampleInfo: WorkspaceInfo = { + name: 'Test Workspace', + directory: '/test/dir', + extra: {}, + } + + const cfg = { + url: 'http://manager.test:5003', + token: 'tok-abc', + } + + it('returns project directory in configured workspace info', async () => { + const { makeAdaptor } = await import('../src/index.js') + const project = { slug: '42', name: 'Test Project', directory: '/workspace/repos/test' } + const adaptor = makeAdaptor(cfg, project) + const result = adaptor.configure(sampleInfo) + expect(result.directory).toBe('/workspace/repos/test') + }) + + it('returns extra with slug in configured workspace info', async () => { + const { makeAdaptor } = await import('../src/index.js') + const project = { slug: '42', name: 'Test Project', directory: '/workspace/repos/test' } + const adaptor = makeAdaptor(cfg, project) + const result = adaptor.configure(sampleInfo) + expect(result.extra).toEqual({ slug: '42' }) + }) +}) + +